JAVA - 当用户点击回车时按下按钮 java swing

JAVA - Press button when user hits enter java swing

我有一个猜谜游戏,用户输入一个从 1 到 10 的数字,然后尝试猜对一个。

我在 window 中有一个开始新游戏的按钮:

    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);

我希望用户按下 Enter 并点击按钮。

这是all my code:. This is what the window with the play again button looks like:

当用户点击那个按钮时,我如何才能点击该按钮?

当答案正确时,您可以将JFrame的默认按钮设置为重播按钮。

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

调用newGame方法时,可以将默认按钮重置为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);
}