//本人没写过。。只是书上有。。。就写给你看看。。使用appletviewer运行该程序 //我还没运行你运行看看。。。 import java.awt.*; import java.awt.event.*; import java.applet.Applet;
public class CalulatorApplet extends Applet implements ActionListener { private TextField display; private double arg = 0; private String op = "="; private boolean start = true; public void init () { setLayout (new BorderLayout() ); display = new TextField("0"); display.setEditable(true); add(display,"north"); Panel p = new Panel(); p.setLayout(new GridLayout (4,4)); String buttons = "123+456-789*0.=/"; for (int i = 0; i <buttons.length(); i++ ){ Button b = new Button(buttons.substring(i,i+1)); p.add(b); b.addActionListener(this);//在按钮上注册动作监听器 } add(p,"Center"); }//end init() public void actionPerfored(ActionEvent ev){ Stirng s = ev.getActionCommand(); if('0' <= s.charAt(0) && s.charAt(0) <= '9' || s.equals(".")){ if(start) display.setText(s); else display.setText(display.getText()+s); start = false; } else { if(start){ if(s.equals("-")){ display.setText(s); start = false; } else { op = s; } } else { calculate (Double.parseDouble(display.getText())); op = s; start = true; } } }//end actionPerformed() public void calculate(double n){ if(op.equals("+")) arg += n; else if(op.equals("-")) arg -= n; else if(op.equals("*")) arg *= n; else if(op.equals("/")) arg /= n; else if(op.equals("=")) arg = n; display.setText(double.toString(arg)); } }//end CaculatorApplet class