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
How to get a JTextField to respond to the enter key
提问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 KeyListener
for Swing
components.
忘记使用KeyListener
forSwing
组件。
This listener was designed for use with AWT
components does not provide a reliable interaction mechanism for JTextComponents
.
此侦听器专为与AWT
组件一起使用而设计,不为 提供可靠的交互机制JTextComponents
。
Use an ActionListener
instead - on the vast majority of systems an ActionEvent
is dispatched by the JTextField
when enter is pressed.
使用ActionListener
替代 - 在绝大多数系统上, anActionEvent
由JTextField
按下 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());
}
}
});