JAVA-当用户点击enter JAVA swing时按下按钮

JAVA-当用户点击enter JAVA swing时按下按钮,java,swing,jframe,Java,Swing,Jframe,我有一个猜谜游戏,用户输入一个从1到10的数字,然后试着猜正确的数字 我在窗口中有一个按钮,用于启动新游戏: btnPlayAgain = new JButton("Play Again!"); btnPlayAgain.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newGame();

我有一个猜谜游戏,用户输入一个从1到10的数字,然后试着猜正确的数字

我在窗口中有一个按钮,用于启动新游戏:

    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键并单击按钮

这是。这是带有“再次播放”按钮的窗口的外观:


当用户点击“再次播放”按钮时,如何让该按钮单击?

当答案正确时,您可以将
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);
}