Share the post "Simulate ENTER Key On Any Component Using Java"
Simulating input events in any component in Java can be done by using the Robot class. But what if I do not want to use the Robot class? Well, it is possible. The code below simulates an ENTER keypress event. The KeyEvent object created can easily be changed to cover any key event that you want. If you noticed, one of the parameters has a value of -1. This means that neither ALT, SHIFT or CONTROL is included.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static void simulateEnterKey(Component c) { try { KeyEvent ke = new KeyEvent(c, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), -1, KeyEvent.VK_ENTER, (char) KeyEvent.VK_ENTER); c.requestFocusInWindow(); dispatchEvent(ke, c); } catch (Exception ex) { } } private static void dispatchEvent(final KeyEvent ke, final Component comp) throws Exception { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeAndWait(new Runnable () { @Override public void run() { comp.dispatchEvent(ke); } }); } else { comp.dispatchEvent(ke); } } |
hello hello just thanks for your information about java, by misfortune. the code does not work for now … not what would be the error .. step down here a fragment of code. thanks ..
has you somethig tip..my be…thank
private void CodigoBarraActionPerformed(java.awt.event.ActionEvent evt) {
simulateEnterKey(CodigoBarra);
busquedaCliente();
sumar_stock();
}
public static void simulateEnterKey(Component c) {
try {
KeyEvent ke = new KeyEvent(c, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), -1, KeyEvent.VK_ENTER, (char) KeyEvent.VK_ENTER);
c.requestFocusInWindow();
dispatchEvent(ke, c);
} catch (Exception ex) { }
}
private static void dispatchEvent(final KeyEvent ke, final Component comp) throws Exception {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeAndWait(new Runnable () {
@Override
public void run() {
comp.dispatchEvent(ke);
}
});
} else {
comp.dispatchEvent(ke);
}
}