我使用GUI创建了一个“计算器”。但是当我使用我的输入按钮时,无论我按哪个操作员,它总是打印出两个数字的产品。为什么我的按钮不能执行正确的操作?
class Calculator extends JFrame implements ActionListener{
JTextfield firstN, secondN;
JButton addButton, subButton, divButton, mulButton, enter;
JLabel result;
Calculator(){
// here I initialized all the components and added buttons/ActionListeners
}
public void actionPerformed(ActionEvent e) {
int first = Integer.parseInt(firstN.getText());
int second = Integer.parseInt(secondN.getText());
int value = 0;
if(e.getSource() == addButton){
value = first + second;
}else if(e.getSource() == subButton){
value = first - second;
}else if(e.getSource() == divButton){
value = first/second;
}else{
value = first*second;
}
if(e.getSource() == enter)
result.setText(value + "");
}
没有输入按钮,计算器工作正常。我尝试了一个do-while循环,但结果是无限的..
我想我得到了错误的if/else语句,但其中一个前4个语句总是被执行,所以最后一个也应该工作尽我所知...
完美运作!快速偏离主题:为什么每次单击按钮时都会重置“值”?为什么变量应该是一个类级别的字段? –
@ marie.ellaZ发生这种情况是因为每次单击按钮时,actionPerformed()方法都会从乞讨执行到结束。所以如果它包含'int value = 0'这一行,每次点击都会将它设置为零。如果您想保留点击次数之间的值,则必须将其存储在此方法之外的某个位置,并且类级别字段对此非常明显。 –