我是Java GUI编程的新手,我已经开始编写一个具有多个JButton的GridBagLayout GUI的程序。我已经为每个按钮添加了一个动作监听器,但是当我单击任何1按钮时,程序会响应,就像我点击了EVERY SINGLE按钮一样,包括甚至不在GUI上的按钮。我在下面发布了我的代码的相关部分。整个程序很长,所以我将下面的代码仅限于处理JButton的段。另请注意,我只想使用1个actionPerformed()方法,并测试源而不是在每个addActionListener()之后直接使用actionPerformed()方法。
buttons = new JButton[buttonNumber];
for (int i = 0; i < buttonNumber; i++)
{
buttons[i] = new JButton();
}
然后,在我获得srting []对象buttonLabels就绪之后:
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
答案 0 :(得分:2)
if (e.getSource() == buttons[i]);
// remove the semi-colon here ---^