Showing posts with label jbutton. Show all posts
Showing posts with label jbutton. Show all posts

Friday, 11 January 2008

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 a Swing JButton so the button behaves as though it was clicked when the key is pressed:

JButton saveButton = new JButton(new SaveAction());
InputMap inputMap = saveButton.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW);
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
inputMap.put(enter, "ENTER");
saveButton.getActionMap().put("ENTER", new ClickAction(saveButton));

...

public class ClickAction extends AbstractAction {
private JButton button;

public ClickAction(JButton button) {
this.button = button;
}

public void actionPerformed(ActionEvent e) {
button.doClick();
}
}

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.