Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Adding a Key Binding Globally (to an entire JFrame)

843804Jul 10 2005 — edited Jul 10 2005

Hi, all. I'm trying the ever-so-common task of adding a global key binding to my little Swing app. I just wrote a very basic image converter for an obscure multi-frame format and one of the users requested that I add a simple feature: when control-N is pressed, the a new document is created (just as if the user had selected New from the File menu).

I've read the Swing keybinding tutorial and I've tried to write a method to neatly contain the operation. The method is as follows:

    public static void setKeystrokeForAction(JFrame jframe, KeyStroke keystroke, Action action)
    {
        jframe.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keystroke, action.getValue(Action.NAME));
        jframe.getRootPane().getActionMap().put(action.getValue(Action.NAME), action);
    }

This doesn't seem to work. I was under the impression that this would somehow allow any component focused in the frame to respond to the specified KeyStroke (in this case, control-N) and react by executing the Action provided (in this case, an action which calls the new document method in my application). However, I press control-N with various focused components and nothing happens.

I know that the Action is sound because selecting the File : New item (which uses the same Action object) works just fine. The KeyStroke is constructed as follows:

KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_DOWN_MASK)

What am I missing?

Thanks!

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 7 2005
Added on Jul 10 2005
2 comments
43 views