Sometimes we want a key combination to perform a certain action regardless of what component has focus. Achieving this goal requires us to do two things.
- Add the required key stroke to the components key map
- Add the required action to the components action map
The “action key” is the link between the input map and the action map. When a key matches a key in the components input map the associated action key is used to look up the action in the action map.
The following example shows how to map an action to get performed whenever Ctrl-H is pressed within the focussed window.
// Get the KeyStroke for our hot key KeyStroke ctrlH = KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_DOWN_MASK, true); // Get the input map for our component // In this case we are interested in key strokes in the focussed window InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); // Map the key stroke to our "action key" (see below) inputMap.put(ctrlH, "my_action"); // Get the action map for our component ActionMap actionMap = panel.getActionMap(); // Add the required action listener to out action map actionMap.put("my_action", actionListener);
Leave a Reply
You must be logged in to post a comment.