Java – Setting up application wide Key Listeners

javakeyboard shortcutsswing

How do i setup application wide key listeners (keyboard shortcuts), so that when a key combination (e.g. Ctrl + Shift + T) is pressed, a certain action is invoked in a Java application.

I know keyboard shortcuts can be set JMenuBar menu items, but in my case the application does not have a menu bar.

Best Answer

Check out the How To Use Key Bindings section of the Java tutorial.

You need to create and register an Action with your component's ActionMap and the register a (KeyStroke, Action Name) pair in one of your application's component's InputMaps. Given that you don't have a JMenuBar you could simply register the key bindings with a top-level JPanel in your application.

For example:

Action action = new AbstractAction("Do It") { ... };

// This is the component we will register the keyboard shortcut with.
JPanel pnl = new JPanel();

// Create KeyStroke that will be used to invoke the action.
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK);

// Register Action in component's ActionMap.
pnl.getActionMap().put("Do It", action);

// Now register KeyStroke used to fire the action.  I am registering this with the
// InputMap used when the component's parent window has focus.
pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "Do It");