希望大家能提出些建议,我来改进。
代码如下:
import java.awt.*;
import java.awt.event.*;
class Calculate extends Frame implements ActionListener {
TextField t1 = new TextField(5);
TextField t2 = new TextField(2);
TextField t3 = new TextField(5);
TextField t4 = new TextField(10);
Label L1 = new Label("=");
Button btn = new Button("计算");
Label L2 = new Label(" 第一个框里添被运算数,第二个框里添运算符仅限+、-、*、/四个, 第三个框里添运算数,");
Label L3 = new Label(" 按计算按扭结果会在第四个框中显示出来。老师让我做个类似windows计算器的GUI程序,呵呵,偷懒了。
");
public Calculate() {
setLayout(new FlowLayout());
add(t1);
add(t2);
add(t3);
add(L1);
add(t4);
add(btn);
add(L2);
add(L3);
btn.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
float x,y;
double result = 0;
String op;
try {
x = Float.parseFloat(t1.getText());
y = Float.parseFloat(t3.getText());
op = t2.getText();
if (op.equals("+")) {result = x + y;}
else if (op.equals("-")) {result = x - y;}
else if (op.equals("*")) {result = x * y;}
else if (op.equals("/")) {result = x / y;}
t4.setText(Double.toString(result));
}
catch(Exception ee){
t4.setText("数据类型错误!");
}
}
public static void main (String args[]) {
Calculate mainFrame = new Calculate();
mainFrame.setSize(600,150);
mainFrame.setTitle("musicyxy的计算器程序");
mainFrame.setVisible(true);
}
}