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]

# 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?
# 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;
}
});