在JTextField聚焦时接收KeyEvent

时间:2015-08-06 18:42:50

标签: java swing jtextfield keylistener

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

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

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

我已经看到了:

How do you make key bindings for a java.awt.Frame?

How do you make key binding for a JFrame no matter what JComponent is in focus?

但我还没有解决问题,焦点管理可能有问题。

我尝试了以下代码:

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

    }

}

我该怎么办?

由于

1 个答案:

答案 0 :(得分:1)

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