Java Swing JButton keyboard shortcuts

It took ages to work out how to do this, so I decided to post it here in the hope someone else will benefit. Here's how to install a keyboard shortcut to a Swing JButton so the button behaves as though it was clicked when the key is pressed.

  1. JButton saveButton = new JButton(new SaveAction());
  2. InputMap inputMap = saveButton.getInputMap(
  3. JButton.WHEN_IN_FOCUSED_WINDOW);
  4. KeyStroke enter = KeyStroke.getKeyStroke(
  5. KeyEvent.VK_ENTER, 0);
  6. inputMap.put(enter, "ENTER");
  7. saveButton.getActionMap().put("ENTER",
  8. new ClickAction(saveButton));
  9.  
  10. ...
  11.  
  12. public class ClickAction extends AbstractAction {
  13. private JButton button;
  14.  
  15. public ClickAction(JButton button) {
  16. this.button = button;
  17. }
  18.  
  19. public void actionPerformed(ActionEvent e) {
  20. button.doClick();
  21. }
  22. }
  23.  

A complete example is in shortcut-buttons-src-0.1.jar. The download includes an ant build file. To compile and run, just type "ant run" at the shell prompt. You will need ant and a JDK >= 1.5 installed.

Source download: shortcut-buttons-src-0.1.jar