Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up application wide Key Listeners

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.

like image 838
n002213f Avatar asked Aug 05 '09 07:08

n002213f


1 Answers

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");
like image 172
Adamski Avatar answered Oct 01 '22 02:10

Adamski