网上找的,如果你是要求的这样的,自己写也要好一会:
import java.awt.*;
import java.awt.event.*;
public class Calculator {
private Frame f;
private TextField tf = new TextField(30);
private long result;
private boolean append = false;
private Button[] btn = new Button[15];
private char operator = '=';
public static void main(String[] args) {
new Calculator().go();
}
public Calculator() {
initComponent();
}
private void initComponent() {
f = new Frame("Java Calculator");
f.setLayout(new BorderLayout()); // The frame uses BorderLayout
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
Panel centerPanel = new Panel();
centerPanel.setLayout(new GridLayout(5, 3)); // The panel uses GridLayout
NumberListener nl = new NumberListener();
OperatorListener ol = new OperatorListener();
btn[10] = new Button("+");
btn[11] = new Button("-");
btn[12] = new Button("*");
btn[13] = new Button("/");
btn[14] = new Button("=");
for (int i = 0; i <= 9; i++) {
btn[i] = new Button(String.valueOf(i));
centerPanel.add(btn[i]);
btn[i].addActionListener(nl);
if (i % 2 == 1) {
centerPanel.add(btn[(i + 19) / 2]);
btn[(i + 19) / 2].addActionListener(ol);
}
}
f.add(centerPanel, BorderLayout.CENTER);
Panel northPanel = new Panel();
tf.setEditable(false);
northPanel.add(tf);
f.add(northPanel, BorderLayout.NORTH);
}
public void go() {
f.pack();
f.setVisible(true);
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!append) {
tf.setText("");
append = true;
}
String s = tf.getText();
s += e.getActionCommand();
tf.setText(s);
if (!btn[10].isEnabled()) {
for (int i = 10; i <= 14; i++)
btn[i].setEnabled(true);
}
}
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!append)
return;
for (int i = 10; i <= 14; i++)
btn[i].setEnabled(false);
String s = tf.getText();
long num = Long.parseLong(s);// get the number of textfield
append = false; // set append
switch (operator) {
case '+':
result += num;
break;
case '-':
result -= num;
break;
case '*':
result *= num;
break;
case '/': {
if (num == 0)
result = 0;
else
result /= num;
break;
}
case '=':
result = num;
break;
}
tf.setText(String.valueOf(result));
// set the value of result to textfield
String op = e.getActionCommand();
operator = op.charAt(0); // set operator
}
}
}