// 谢谢各位大虾帮忙修改下```~~
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Calculator extends Applet
implements ActionListener
{
//弹出窗口
private Frame calFrame = new CalFrame();
public void init()
{
//弹出的按钮
Button calBtn = new Button("打开计算器");
calBtn.addActionListener(this);
add(calBtn);
}
public void actionPerformed(ActionEvent e)
{
//弹出窗口没有被显示,则显示,否则关闭
if(calFrame.isVisible())
calFrame.setVisible(true);
else
calFrame.setVisible(true);
}
private void jbInit() throws Exception {
}
class CalFrame extends Frame implements ActionListener
{
private TextField display=null;
private double arg1=0;
private StringBuffer arg2 = new StringBuffer();
private char op='=';
public CalFrame()
{
setTitle("计算器");
setSize(250,250);
setLayout(new BorderLayout(5,5));//采用边界布局
//菜单
MenuBar mb = new MenuBar();
Menu mEdit = new Menu("编辑");
MenuItem mCopy = new MenuItem("复制");
mCopy.addActionListener(calFrame);//此时对象??
MenuItem mPaste = new MenuItem("粘贴");
mPaste.addActionListener(calFrame);
mEdit.add(mCopy);
mEdit.add(mPase);
Menu mSearch = new Menu("查找");
MenuItem mQuit = new MenuItem("退出");
mCopy.addActionListener(calFrame);
mSearch.add(mQuit);
Menu mHelp = new Menu("帮助");
MenuItem mAbout = new MenuItem("关于");
mAbout.addActionListener(calFrame);
mHelp.add(mAbout);
setMenuBar(mb);
setVisible(true);
//输出窗口
display = new TextField("结果显示");
display.setEditable(false);
add(display,"North");
//数字按键面版
Panel keypad = new Panel();
keypad.setLayout(new GridLayout(4,4));
//添加数字和运算符按键
String keys="789/456*123-0.=+";
for(int i =0;i<keys.length();i++)
{
Button btn = new Button(keys.substring(i,i+1));
keypad.add(btn);
//为按键添加事件监听器
btn.addActionListener(this);
}
add(keypad,"Center");
}
public void actionPerformed(ActionEvent e)
{
//响应按键,如果是数字则连接到StringBuffer中,
//如果是运算符则进行运算。
String key = e.getActionCommand();
char c = key.charAt(0);
if((c>='0' &&c<='9'||c=='.'||
(c=='-'&& arg2.length()==0)))
{
arg2.append(c);
display.setText(arg2.toString());
}
else
{
calculator(Double.parseDouble(arg2.toString()));
op=c;
arg2.setLength(0);
if(c=='=')
arg2.append(arg1);
};
}
public void calculator(double arg2)
{
//计算
switch(op)
{
case'+':arg1+=arg2;break;
case'-':arg1-=arg2;break;
case'*':arg1*=arg2;break;
case'/':arg1/=arg2;break;
case'=':arg1 =arg2;break;
default: break;
}
display.setText(""+arg1);
}
}}