1

I have a guessing game where the user enters a number from 1 to 10 and tries to guess the right one.

I have a button in a window that starts a new game:

    btnPlayAgain = new JButton("Play Again!");
    btnPlayAgain.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            newGame();
        }
    });
    btnPlayAgain.setBounds(146, 115, 141, 21);
    getContentPane().add(btnPlayAgain);
    btnPlayAgain.setVisible(false);

I want the user to press Enter and have the button get clicked.

This is all my code:. This is what the window with the play again button looks like: Guessing Game Window

How can I get that play again button to click when the user hits that button?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Tim Dunphy
  • 685
  • 2
  • 10
  • 25

1 Answers1

2

When the answer is correct, you can set the default button of the JFrame to the play again button.

btnGuess.setVisible(false);
txtGuess.setVisible(false);
message = guess + " is correct. Let's play again!";
btnPlayAgain.setVisible(true);
getRootPane().setDefaultButton(btnPlayAgain);

When the newGame method is called, you can reset the default button to null.

public void newGame() {
    numberOfTries = 8;
    theNumber = (int) (Math.random() * 10 + 1);
    btnGuess.setVisible(true);
    txtGuess.setVisible(true);
    btnPlayAgain.setVisible(false);
    lblOutput.setText("Enter a number above and click Guess!");
    getRootPane().setDefaultButton(null);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80