【发布时间】:2013-06-25 06:18:05
【问题描述】:
我的程序有一个问题,该程序包含一个单独的类Calculator,它应该实现一个能够使用+ 和* 操作类型为double 的计算器。
我也为那个计算器写了一个图形用户界面,它已经很好用了,但是按钮不起作用,虽然我已经实现了这个功能
public void actionPerformed(ActionEvent e)
我猜这个错误一定是在这个函数的某个地方。我只是不知道为什么按钮的功能不起作用。这是代码。
public class Calculator extends JFrame implements ActionListener {
Calculator () {}
JTextField parameter1;
JTextField parameter2;
JTextField ergebnis;
JFrame window;
Container cont;
/* this function works fine */
public void calculator_GUI() {
builds the GUI of the calculator,
this.window = new JFrame("Calculator");
window.setSize(300,300);
this.parameter1 = new JTextField("Parameter1...", 10);
parameter1.addActionListener(this);
this.parameter2 = new JTextField("Parameter1...", 10);
parameter2.addActionListener(this);
this.ergebnis = new JTextField("Ergebnis...", 5);
ergebnis.addActionListener(this);
JButton multiplizieren = new JButton("*");
parameter1.addActionListener(this);
JButton addieren = new JButton("+");
parameter1.addActionListener(this);
JButton clear = new JButton("clear");
parameter1.addActionListener(this);
this.cont = window.getContentPane();
FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT);
cont.setLayout(flowLayout);
cont.add(parameter1);
cont.add(parameter2);
cont.add(ergebnis);
cont.add(multiplizieren);
cont.add(addieren);
cont.add(clear);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);;
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if (label.equals("*")) {
String a = parameter1.getText();
String b = parameter2.getText();
double zahl1=Double.parseDouble(a);
double zahl2=Double.parseDouble(b);
double result = zahl1*zahl2;
String c = String.valueOf(result);
ergebnis.setText(c);
}
else if (label.equals("+")) {
String a = parameter1.getText();
String b = parameter2.getText();
double zahl1=Double.parseDouble(a);
double zahl2=Double.parseDouble(b);
double result = zahl1+zahl2;
String c = String.valueOf(result);
ergebnis.setText(c);
}
else if (label.equals("clear")) {
String z = "";
ergebnis.setText(z);
}
else {
window.dispose();
}
}
public static void main (String[] args) {
Calculator MyCalculator = new Calculator();
MyCalculator.calculator_GUI();
}
}
【问题讨论】:
-
"已经可以正常工作,但是按钮不能正常工作" - 然后就不能正常工作了:D
-
1) 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。 2) 不要扩展框架或其他顶级容器。而是创建并使用一个实例。
-
定义“不起作用”。处理程序中的断点是否命中?会发生什么?
标签: java swing user-interface actionlistener actionevent