Reputation: 41
This is a lab for school that I'm struggling with, the code is making a game of hangman, and when the "brain" program says the game is over, all of the letter buttons are supposed to be disabled.
relevant code sections:
the buttons:
class ActionButton extends JButton implements ActionListener{
private String name;
private char t;
public ActionButton(String s){
super(s);
name = s;
t = name.charAt(0);
}
@Override
public void actionPerformed(ActionEvent e) {
ido.newLetter(t);
this.setEnabled(false);
LovesMePanel.this.update();
}
}
the update method:
public void update(){
answers = ido.getAnswer();
flower.setTriesLeft(ido.getTriesLeft());
progress.setText(answers);
if(ido.gameOver()){
// This is where I need to deactivate the buttons
if(ido.hasWon()){
}
}
else if(triesLeft == 0){
}
}
the buttons are all created in a loop in the LoveMePanel that holds all of the other panels. Is there a way to reference them all or disable them all when the game is over? If not, how should I change my code so that it would be possible to do that?
Upvotes: 1
Views: 4717
Reputation: 4588
See the setEnabled() method for JButton. You can:
ArrayList
while creating them and then iterate over it and disable one by oneFeel free to choose the one you like best.
Upvotes: 2
Reputation: 2845
If you put your buttons in a Collection
, you can iterate through them and disable them all that way. I.e.,
for (JButton b : myButtons) {
b.setEnabled(false)
}
If not, you have 26 disable statements to write.
Upvotes: 8
Reputation: 1142
how about getting the children of the root panel by calling getComponents and iterating over them recursively and finding JButtons and disabling them as you find them?
Upvotes: 0