user2218030
user2218030

Reputation: 41

Is there a way to disable all buttons with a method?

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

Answers (3)

svz
svz

Reputation: 4588

See the setEnabled() method for JButton. You can:

  1. Add your Buttons to an ArrayList while creating them and then iterate over it and disable one by one
  2. Get children of a JPanel, iterate over them, check if it's a button and disable it
  3. Put a Glass Pane on top of your Burrons to intercept the incoming events

Feel free to choose the one you like best.

Upvotes: 2

Nick
Nick

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

Farzad
Farzad

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

Related Questions