以编程方式触发JTextField中的键事件? [英] Programmatically trigger a key events in a JTextField?
问题描述
如何以编程方式触发正在 ENTER 上侦听事件的 JTextField
上的按键事件?
How do I programmatically trigger a key pressed event on a JTextField
that is listening for events on the ENTER?
我的 JTextField
上的关键事件的监听器声明如下:
The listener for key events on my JTextField
is declared as follows:
myTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
// Do stuff
}
}
});
谢谢。
推荐答案
-
不要在
JTextField
上使用KeyListener
添加ActionListener
将在按下 ENTER 时触发(感谢@robin +1获取建议)Do not use
KeyListener
onJTextField
simply addActionListener
which will be triggered when ENTER is pressed (thank you @robin +1 for advice)JTextField textField = new JTextField(); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //do stuff here when enter pressed } });
-
要触发
KeyEvent
使用requestFocusInWindow()
关于组件并使用Robot
类来模拟按键 To trigger
KeyEvent
userequestFocusInWindow()
on component and useRobot
class to simulate key press如下所示:
textField.requestFocusInWindow(); try { Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); }
示例:
import java.awt.AWTException; import java.awt.Robot; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class Test { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField textField = new JTextField(); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { System.out.println("Here.."); } }); frame.add(textField); frame.pack(); frame.setVisible(true); textField.requestFocusInWindow(); try { Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); } } }); } }
更新:
像@Robin和@mKorbel这样的人建议您可能需要
DocumentListener
/DocumentFiler
(过滤器允许在JTextField
更新之前进行验证。)As others like @Robin and @mKorbel have suggested you might want a
DocumentListener
/DocumentFiler
(Filter allows validation beforeJTextField
is updated).你需要在数据验证事件IMO。
You will need this in the event of data validation IMO.
看到类似的问题 here
它显示了如何将
DocumentFilter
添加到JTextField
进行数据验证。文件过滤的原因就像我说的那样,在显示chnage之前允许验证更有用IMOit shows how to add a
DocumentFilter
to aJTextField
for data validation. The reason for document filter is as I said allows validation before chnage is shown which is more useful IMO这篇关于以编程方式触发JTextField中的键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!