当JTextField聚焦时接收KeyEvents



我正在开发一款游戏,我有一个JFrame,它在JTextField中接收玩家的名字。

我想要的是通过按JButton或按ENTER键来关闭窗口的可能性。

当窗口打开时,JTextField必须有焦点(光标应该出现在组件中)。

我已经看到了:

如何为java.awt.Frame做键绑定?

无论焦点是什么JComponent,如何为JFrame绑定键?

但我还没有解决这个问题,可能是焦点管理出了问题。

我尝试了以下代码:

public class PlayerNameWindow extends JFrame implements KeyListener {
    private String playerName;
    private JLabel backgroundLabel;
    private JLabel enterNameLabel;
    private JButton confirmButton;
    private JTextField nameField;
    private Image background;
    public PlayerNameWindow() {
        initComponents();
    }
    private void initComponents() {
        backgroundLabel = new JLabel();
        enterNameLabel = new JLabel();
        confirmButton = new JButton();
        nameField = new JTextField();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 200));
        setResizable(false);
        getContentPane().setLayout(null);
        addKeyListener(this);
        enterNameLabel.setFont(new Font("Tahoma", 1, 18)); 
        enterNameLabel.setForeground(new Color(255, 255, 255));
        enterNameLabel.setText("Enter your name:");
        getContentPane().add(enterNameLabel);
        enterNameLabel.setBounds(40, 80, 160, 30);
        confirmButton.setText("Confirm");
        confirmButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                confirmButtonMouseClicked(evt);
           }
        });
        confirmButton.setBounds(160, 150, 90, 25);
        getContentPane().add(confirmButton);
        getContentPane().add(nameField);
        nameField.setBounds(220, 80, 140, 30);
        getContentPane().add(backgroundLabel);
        backgroundLabel.setBounds(0, 0, 400, 200);
        pack();
        setLocationRelativeTo(null); 
    }                      
    private void confirmButtonMouseClicked(MouseEvent evt) { 
        confirmAction();
    }         
    private void confirmAction() {
        playerName = nameField.getText();
        System.exit(0);
    }
    public String getPlayerName() {
          return this.playerName;
    }
    public void keyPressed(KeyEvent e) {
         int code = e.getKeyCode();
         if (code == KeyEvent.VK_ENTER)
             System.exit(0);
    }
    public void keyReleased(KeyEvent e) {
           //do-nothing
    }
    public void keyTyped(KeyEvent e) {
          //do-nothing
    }
}

我该怎么办?

谢谢

添加keyListener到JTextField。在您的代码中,nameField.addKeyListener(this);

最新更新