1

2つのボタンと表示された変数(num)を備えた単純なJavaGUIプログラムに取り組んでいます。ボタンの名前は「increment」および「decrement」であり、それらの機能は、最初は50に設定されている表示された変数numをインクリメントまたはデクリメントすることです。

プログラムはコンパイルされますが、インクリメントボタンとデクリメントボタンは、numの値を1つではなく2つ増やしたり減らしたりします。コード「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);
    }
}

私はあなたが提供できるどんな助けにも感謝します。

4

2 に答える 2

3

両方にアクションリスナーの2つのインスタンスをアタッチしました。必要なのは、それぞれ1つだけです。

increment.addActionListener (new incListener()); 
decrement.addActionListener (new decListener()); 
//Remove the extra ones
//increment.addActionListener (new incListener()); 
//decrement.addActionListener (new decListener()); 
于 2012-10-02T22:14:27.283 に答える
3

各ボタンにインクリメントリスナーとデクリメントリスナーを2回追加しました。

于 2012-10-02T22:15:01.760 に答える