我正在开发一个带有两个按钮和一个显示变量(num)的简单 java GUI 程序。这些按钮被命名为“增量”和“减量”,它们的功能是增加或减少显示的变量 num,初始设置为 50。
虽然程序会编译,但递增和递减按钮将 num 的值增加/减少 2 而不是 1。我已经尝试过诸如将代码“num++”更改为“num = num + 1”之类的方法,但这仍然会导致按钮增加 2。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment_4 extends JFrame {
private int num = 50;
private JButton increment;
private JButton decrement;
private JLabel label;
private JPanel buttonPanel;
private JPanel displayPanel;
public Assignment_4() {
increment = new JButton ("Increment");
decrement = new JButton ("Decrement");
increment.addActionListener (new incListener());
decrement.addActionListener (new decListener());
increment.addActionListener (new incListener());
decrement.addActionListener (new decListener());
num = 50;
label = new JLabel ("" + num);
buttonPanel = new JPanel();
displayPanel = new JPanel();
buttonPanel.add(increment);
buttonPanel.add(decrement);
displayPanel.add(label);
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.CENTER);
add(displayPanel, BorderLayout.NORTH);
}
private class incListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
num++;
label.setText("" + num);
}
}
private class decListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
num--;
label.setText("" + num);
}
}
public static void main(String[] args) {
Assignment_4 win = new Assignment_4();
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.pack();
win.setVisible(true);
}
}
感谢您提供的任何帮助。