动作监听器的行为就像我点击了每一个按钮,而不是只点击了1个



我是Java GUI编程的新手,我已经开始编写一个带有多个JButton的GridBagLayout GUI程序。我为每个按钮添加了一个动作侦听器,但当我单击ANY 1按钮时,程序的响应就像我单击了每个单个按钮一样,包括甚至不在GUI上的按钮。我已经在下面发布了我的代码的相关部分。整个程序相当长,所以我将下面的代码仅限于处理JButton的部分。还要注意,我只想使用1 actionPerformed()方法,并测试源代码,而不是在每个addActionListener()之后直接使用actionPerforme()方法。

buttons = new JButton[buttonNumber];
for (int i = 0; i < buttonNumber; i++)
{
    buttons[i] = new JButton();
}

然后,在我准备好srting[]对象按钮标签后:

for (int i = 0; i < buttonNumber; i++)
{
    buttons[i].setText(buttonLabels[i]);
}

然后,稍后:

for(int i = 0; i < buttonNumber; i++)
{
    if(buttonLabels[i] != null && i < 18)
    {
        decorator.positionButtons(i, writer.currentNumberOfButtons);
        c.gridx = decorator.xPosition;
        c.gridy = decorator.yPosition;
        c.gridwidth = 1;
        Dimension d = new Dimension(buttonWidth, decorator.buttonHeight);
        buttons[i].setPreferredSize(d);
        buttons[i].addActionListener(this);
        windowContents.add(buttons[i], c);
    }
    if(i == 18)
    {
        c.gridx = 0;
        c.gridy = (decorator.yPosition + 1);
        buttons[i].addActionListener(this);
        windowContents.add(buttons[i], c);
    }
    else if (i == 19)
    {
        c.gridx = 2;
        c.gridy = (decorator.yPosition + 1);
        buttons[i].addActionListener(this);
        windowContents.add(buttons[i], c);
    }
}

最后:

public void actionPerformed(ActionEvent e)
{
    boolean buttonClicked = false;
    int buttonIndex = -1;
    for(int i = 0; i < buttonNumber; i++)
    {
        if (e.getSource() == buttons[i]);
        {
            buttonIndex = i;
            buttonClicked = true;
            System.out.println("Here at button" + buttonIndex");
        }
    }
}

这个程序最初只在屏幕上放了6个按钮,当我点击其中的任何一个时,我得到的结果是:

Here at button0
Here at button1
Here at button2
Here at button3
Here at button4
Here at button5
Here at button6
Here at button7
Here at button8
Here at button9
Here at button10
Here at button11
Here at button12
Here at button13
Here at button14
Here at button15
Here at button16
Here at button17
Here at button18
Here at button19
 if (e.getSource() == buttons[i]);
// remove the semi-colon here ---^ 

最新更新