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.
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 InputMap
s. 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With