Here's my code :
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
panel_1.add(button);
}
}
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//If Button is clicked, make the button unclickable
if(button == (JButton)e.getSource())
{
button.setEnabled(false);
}
}
});
I want to make any JButton I click from this 10 x 10 grid button layout unclickable; however, this method only makes no other that the right button unclickable, What's wrong? I have put the ActionListener outside the for-Loop that is responsible for making the buttons. I don't know what's going on.
Here's what it looks like :
Edit: bsd code works. Add ActionListener before adding the buttons or something along those lines.
You only add the ActionListener to the last button created.
You need to add the ActionListener to every button created inside the loop.
So the code should be something like:
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
button.setEnabled( false );
}
};
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
panel_1.add(button);
}
}