java 如何让 JTextField 响应回车键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16378888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:48:41  来源:igfitidea点击:

How to get a JTextField to respond to the enter key

javaswingjtextfieldkeylistenerenter

提问by Rabbitman14

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?

所以我想得到一个 JTexField 将其中的文本放入 JTextArea 当光标在其中按下 Enter 键时。任何人都可以帮忙吗?

回答by Reimeus

Forget about using KeyListenerfor Swingcomponents.

忘记使用KeyListenerforSwing组件。

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

此侦听器专为与AWT组件一起使用而设计,不为 提供可靠的交互机制JTextComponents

Use an ActionListenerinstead - on the vast majority of systems an ActionEventis dispatched by the JTextFieldwhen enter is pressed.

使用ActionListener替代 - 在绝大多数系统上, anActionEventJTextField按下 enter 时调度。

myTextField.addActionListener(new ActionListener() {

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

回答by richard ordo?ez

    JTextArea myJTextArea = new JTextArea();
    myJTextArea.setBounds(200, 15, 258, 28);
    myJPanel.add(myJTextArea);

    JTextField myJTextField = new JTextField();
    myJTextField.setBounds(15, 15, 130, 28);
    myJPanel.add(myJTextField);
    myJTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                myJTextArea.setText(myJTextField.getText());
            }
        }
    });