I have added ENTER Key to the default FocusTraversalKeys as such...
private void focus() {
Set forwardKeys = getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
Set newForwardKeys = new java.util.HashSet(forwardKeys);
newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
}
I have a Product Information form that I am going through using the focus but when it comes to a save button I would like to CLICK the button instead of the focus going to the next component.
I have added a KeyPressed and KeyReleased listener to the button and then tried this...
private void saveButtonKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
evt.consume();
saveButton.doClick();
}
}
This same method works on my Text Area BUT the code doesn't do the CLICK instead puts the focus on next component which is also a button.
Please suggest something that would help me achieve the required result. Find below the Image of the form used.
Don't use a KeyListener. Swing was designed to be used with Key Bindings .
Check out Enter Key and Button for some solutions, one using key bindings and the other using a different approach.
Removed the ENTER Key from the SET i defined when button gains Focus and thus it works with the KeyReleased Method now.
private void saveButtonFocusGained(java.awt.event.FocusEvent evt) {
newForwardKeys.remove(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
}
Thank you everyone for your help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.