0

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.

http://tinypic.com/r/33acqy9/5

mKorbel
  • 109,525
  • 20
  • 134
  • 319
HMH
  • 33
  • 6
  • You could set the focus transferal keys for the button to be default (ie `TAB`), meaning that the `ENTER` key will perform as default... – MadProgrammer Jun 23 '13 at 23:44
  • @MadProgrammer That is what I have done already, set Focus Traversal Key of everything in that Frame to include ENTER Key. I want to do "Space bar" effect when it comes to the Button and not transfer Focus to next component. – HMH Jun 24 '13 at 12:47
  • You can set the focus transfer keys for an individual component as well. Have a look at the [answer by kleo](http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/packagingAppsForMac.html) for more details – MadProgrammer Jun 24 '13 at 20:46

2 Answers2

1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Tried using the DefaultButtonListener class in the link you gave but it didn't help. – HMH Jun 24 '13 at 12:48
0

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!

HMH
  • 33
  • 6