How do I programmatically trigger a key pressed event on a JTextField that is listening for events on the ENTER?
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
}
}
});
Thanks.
Do not use
KeyListeneronJTextFieldsimply addActionListenerwhich will be triggered when ENTER is pressed (thank you @robin +1 for advice)To trigger
KeyEventuserequestFocusInWindow()on component and useRobotclass to simulate key pressLike so:
Example:
UPDATE:
As others like @Robin and @mKorbel have suggested you might want a
DocumentListener/DocumentFiler(Filter allows validation beforeJTextFieldis updated).You will need this in the event of data validation IMO.
see this similar question here
it shows how to add a
DocumentFilterto aJTextFieldfor data validation. The reason for document filter is as I said allows validation before chnage is shown which is more useful IMO