Submitting or cancelling form on keypress

Over and over I find myself being unable to find answers to simple and probably many times redone things. Yet another one:

How do I submit or cancel a whole form in Swing by keypress?

I have a form with some fields and two buttons - Save and Cancel. Now I'd like to have the form canceled (basically actions taken like when Cancel is pressed) when the user presses Esc on keyboard. Likewise I'd like the form saved (Save clicked) when the user presses Enter.

Handling KeyPressed or KeyTyped events on the form is useless, since these are fired by the component which currently has focus, which would usually be one of the TextFields. Trying mnemonics on the Cancel (KeyEvent.VK_CANCEL or KeyEvent.VK_ESCAPE) and Save (KeyEvent.VK_ACCEPT or KeyEvent.VK_ENTER) buttons also doesn't work.

How do I achieve that then?

[847 byte] By [Sonica] at [2007-11-26 19:55:30]
# 1
[url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings[/url]
Rodney_McKaya at 2007-7-9 22:48:43 > top of Java-index,Desktop,Core GUI APIs...
# 2
Darn... Thanks.
Sonica at 2007-7-9 22:48:43 > top of Java-index,Desktop,Core GUI APIs...
# 3
I don't know, maybe you can try dialogs for the whole design:[url= http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html]How to Make Dialogs[/url]
Icycoola at 2007-7-9 22:48:43 > top of Java-index,Desktop,Core GUI APIs...
# 4

Dialogs no, they're Frames and suppose to stay this way.

However I am missing something with Key Bindings. There's still the question of focus. Is it possible to gave a global frame key binding (Escape for Cancel for example) to have cancel pressed wherever the focus is at the moment? Or would I have to add that binding to them map of every component in a given frame?

Sonica at 2007-7-9 22:48:43 > top of Java-index,Desktop,Core GUI APIs...
# 5
Did you read the tutorial in the link I gave you?This is explained there.You use the JComponent.WHEN_IN_FOCUSED_WINDOW input map.
Rodney_McKaya at 2007-7-9 22:48:43 > top of Java-index,Desktop,Core GUI APIs...
# 6

HI

you could try class KeyboardFocusManager

KeyboardFocusManager.getCurrentKeyboardFocusManager()

.addKeyEventDispatcher(new KeyEventDispatcher()

{

public boolean dispatchKeyEvent(KeyEvent e)

{

boolean discardEvent = false;

if(!frame.isActive())

{

//if frame is active then only perform the action

return discardEvent;

}

if (e.getID() == KeyEvent.KEY_RELEASED)

{

if (e.getKeyChar() == Event.ESCAPE)

{

frame.dispose();

}

if (e.getKeyChar() == Event.ENTER)

{

//form submit

}

}

return discardEvent;

}

});

Trushanta at 2007-7-9 22:48:44 > top of Java-index,Desktop,Core GUI APIs...