Pierre-luc G.
Pierre-luc G.

Reputation: 3

Action event on a JButton matrix

I can't handle the event in my matrix of JButtons. I need to figure out which button is pressed, then change an objects color to match the button.

I am currently using this code:

private class matrixButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        JButton btn = (JButton) (e.getSource());
        for (int i = 0; i < matrixBouton.length; i++)
        {
            for (int j = 0; j < matrixBouton[i].length; j++)
            {
                btn.equals(matrixBouton[i][j]);
                if (btn.getBackground() == COLOR_NEUTRAL)
                {
                    btn.setBackground(COLOR_PLAYER);
                }
            }
        }
    }
}

Upvotes: 1

Views: 631

Answers (2)

Radu Murzea
Radu Murzea

Reputation: 10900

Another thing you could do is store the coordinates inside the ActionListener:

private class matrixButtonListener implements ActionListener
{
    private int i;
    private int j;

    public matrixButtonListener (int i, int j)
    {
        this.i = i;
        this.j = j;
    }

    public void actionPerformed(ActionEvent e)
    {
        //this gives you the button on which you pressed
        JButton pressedButton = matrixBouton[this.i][this.j];

        if (pressedButton.getBackground() == COLOR_NEUTRAL)
        {
            pressedButton.setBackground(COLOR_PLAYER);
        }
    }
}

You set each Listener like this:

matrixBouton[i][j].addActionListener (new matrixButtonListener (i, j));

There will be i x j instances of the Listener created. Usually this isn't a big deal, unless i x j is really big (3 digits or 4 digits big).

Upvotes: 1

Vishal K
Vishal K

Reputation: 13066

Instead of looping through all JButtons you simply trace the button using evt.getSource(). This will return you the reference to the actual button pressed. And then you can perform as you wish. You can use following simplified code indeed:

private class matrixButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        JButton btn = (JButton) (e.getSource());
        if (btn.getBackground() == COLOR_NEUTRAL)
         {
            btn.setBackground(COLOR_PLAYER);
         }
    }
}

Upvotes: 3

Related Questions