Reputation: 43
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.
Upvotes: 0
Views: 9092
Reputation: 324197
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);
}
}
Upvotes: 3
Reputation: 2727
Since you want to disable all buttons in your panel. The button action listener should be inside the for loop.
button = new JButton();
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);
}
}
});
Upvotes: 2