以编程方式触发JTextField中的键事件?

如何以编程方式触发正在侦听ENTER上的事件的JTextField上的按键事件?

我的JTextField上的键事件的监听器声明如下:

 myTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ENTER) { // Do stuff } } }); 

谢谢。

  • 不要在JTextField上使用KeyListener只需添加ActionListener ,当按下ENTER时会触发(感谢@robin +1获取建议)

     JTextField textField = new JTextField(); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //do stuff here when enter pressed } }); 
  • 要触发KeyEvent在组件上使用requestFocusInWindow()并使用Robot类来模拟按键

像这样:

 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 (filter允许在更新JTextField之前进行validation)。

在IMO数据validation的情况下,您将需要这个。

在这里看到类似的问题

它显示了如何将DocumentFilter添加到JTextField以进行数据validation。 文档过滤的原因就像我说的那样在显示chnage之前允许validation,这是更有用的IMO

您可以自己构造Event,然后在JTextField上调用dispatchEvent。

  KeyEvent keyEvent = new KeyEvent(...); //create myTextField.dispatchEvent(); 

对于KeyEvent的参数,可以引用KeyEvent构造函数