如何让JTextField响应回车键

如何让JTextField响应回车键

问题描述:

所以我希望得到一个JTexField,当按下回车键并将光标放入其中时,将文本放入JTextArea中。任何人都可以帮忙吗?

So I want to get a JTexField to put the text in it into a JTextArea when the enter key is pressed with the cursor in it. Can anyone help?

忘记使用 KeyListener 获取 Swing 组件。

此侦听器设计用于 AWT 组件不为 JTextComponents

This listener was designed for use with AWT components does not provide a reliable interaction mechanism for JTextComponents.

使用 ActionListener 代替 - 绝大多数系统上 ActionEvent $当按下Enter键时, JTextField 将调度c $ c>。

Use an ActionListener instead - on the vast majority of systems an ActionEvent is dispatched by the JTextField when enter is pressed.

myTextField.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
       myTextArea.append(myTextField.getText() + "\n");
    }
});