/Ken/:
>> What about adding the key listener to the JFrame?
>
[quoted text clipped - 5 lines]
> Another example of what I'm after, is a dialog box that will close when
> escape is pressed.
Does it make difference adding the key listener to the JRootPane of
the JFrame?

Signature
Stanimir
>> What about adding the key listener to the JFrame?
>
[quoted text clipped - 7 lines]
>
> -Ken
Here is how I do this.
AbstractAction act = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
myDialog.setVisible(false);
}
};
getRootPane().getActionMap().put("close", act);
int stdMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
InputMap im =
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");

Signature
Bill Tschumy
Otherwise -- Austin, TX
http://www.otherwise.com
Babu Kalakrishnan - 17 Dec 2004 06:13 GMT
>>>What about adding the key listener to the JFrame?
>>
[quoted text clipped - 23 lines]
> getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
> im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");
Much better advice than the KeyListener suggestion, and the right way to
do it when you're using Swing components. I'd like to add one more point
to it though.
While this approach is correct when the action relates to the top level
component - i.e the window or the frame, it may be difficult or even
impossible to add the keybinding if the action relates to some component
that is sitting inside the window - especially when the component in
question is written as an independent class. This is because you'd
normally want to write the Action code in the class itself and specify
the keybinding in the constructor of the class, and tracing the
parentage back to the Frame/Window parent (in order to register it with
the RootPane) may be impossible at that point because the component may
not even have got added to the container hierarchy.
In such situations, it is best to add the KeyBinding to the
WHEN_IN_FOCUSED_WINDOW InputMap of the component. This way you don't
need to know anything about the top level Window at the time that you
apply the binding, but the binding will automatically start working once
the component has been added to the container hierarchy.
To the OP and the posters who suggested the KeyListener solution -
Please go through the Java Tutorial article on KeyBindings - it
describes InputMaps and ActionMaps in full detail.
BK
Ken - 20 Dec 2004 16:29 GMT
> Here is how I do this.
>
[quoted text clipped - 9 lines]
> int stdMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
> InputMap im =
getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
> im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close");
Thanks!
Thats exactly what I was looking for.
-Ken