Search code examples
javajbuttonactionlistener

Action listener behaving like I click every single button instead of just 1


I am fairly new to Java GUI programming, and I have started writing a program that has a GridBagLayout GUI with multiple JButtons. I have added an action listener to each button, but when I click on ANY 1 button, the program responds as though I have clicked on EVERY SINGLE button, including buttons that are not even on the GUI. I have posted the relevant parts of my code below. The entire program is quite long, so I have limited the code below to only the segments dealing with the JButtons. Also note that I want to use just the 1 actionPerformed() method, and test for the source rather than having an actionPerformed() method directly after each addActionListener().

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

Then, after I get the srting[] object buttonLabels ready:

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

Then, later on:

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);
    }
}

And finally:

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");
        }
    }
}

The program initially puts only 6 buttons on the screen, and when I click on any 1 of them, I get the result:

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

Solution

  •  if (e.getSource() == buttons[i]);
    // remove the semi-colon here ---^