Action listener for JButton array

17,364

have you tried:

public void actionPerformed(ActionEvent e){
   if( e.getSource() instanceof JButton) {
       ((JButton)e.getSource()).setBackground(Color.red);
   }
}

One reason why your code might not work is that the JButton[][] you use to create your buttons is local to your MainW constructor. The approach I have provided will allow you to disregard this scoping issue. It will also remove your iterative approach, and replace it with a more efficient solution. In your code, even if the event is triggered by the first item in your list, or even not triggered by one of your buttons, you will always iterate over the entire 2D array and test each.

Share:
17,364
user530809
Author by

user530809

Updated on June 04, 2022

Comments

  • user530809
    user530809 almost 2 years

    Let's say I have a program with 2D array of buttons, and when you click one of them it turns red. I didn't want to declare every single button seperately so I just created JButton[][] array for them. The problem is that I don't know how to use action listener on any of the buttons in the array so it would change the color of this particular button, and none of related questions is relevant to this. I tried to use "for" but it doesn't help:

    package appli;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class MainW extends JFrame implements ActionListener {
    
        public MainW(){
            setSize(640,480);
            setTitle("title");
            setLayout(null);
            JButton[][] btnz = new JButton[5][5];
            for(Integer i=0;i<5;i++)
            {
                for(Integer j=0;j<5;j++)
                {
                    btnz[i][j]= new JButton("");
                    btnz[i][j].setBackground(Color.WHITE);
                    btnz[i][j].setBounds(10+20*i,10+20*j,20,20);
                    add(btnz[i][j]);
                    btnz[i][j].addActionListener(this);
                }
            }
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setVisible(true);
        }
    
        public void actionPerformed(ActionEvent e){
            for(Integer i=0;i<5;i++)
            {
                for(Integer j=0;j<5;j++)
                {
                    if (e.getSource()==btnz[i][j]);
                    {
                        btnz[i][j].setBackground(Color.RED);
                    }
                }
            }
        }
    
    }