Assign accelerator key to a JButton.
Remus Stratulat 2004-08-18
I found myself in search for this answer and not finding I start
digging through java sources and found something that can help in
BasicButtonListener and BasicButtonUI.
The idea is that you can
assign to each JComponent an ActionMap and an InputMap. In InputMap you
associate a key stroke to an action and in ActionMap the action to
whatever actual action you want. But let's see the code:
// setting the button to receive action when F3 is pressed
InputMap keyMap = new ComponentInputMap(button);
keyMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), "action");
ActionMap actionMap = new ActionMapUIResource();
actionMap.put("action", new YourAction());
SwingUtilities.replaceUIActionMap(button, actionMap);
SwingUtilities.replaceUIInputMap(button, JComponent.WHEN_IN_FOCUSED_WINDOW, keyMap);
// setting done
and
that is all. from now on the button will be concider an action whenever
you press F3 regardless of focus in the current window.