(家庭作业)Java GUI:按钮递增/递减2而不是1

时间:2012-10-02 22:12:13

标签: java

我正在开发一个带有两个按钮和一个显示变量(num)的简单java GUI程序。这些按钮被命名为'increment'和'decrement',它们的功能是递增或递减显示的变量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);
    }
}

感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:3)

您已为两者添加了两个动作侦听器实例,您只需要其中一个。

increment.addActionListener (new incListener()); 
decrement.addActionListener (new decListener()); 
//Remove the extra ones
//increment.addActionListener (new incListener()); 
//decrement.addActionListener (new decListener()); 

答案 1 :(得分:3)

您已为每个按钮添加了两次递增和递减侦听器。