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.

8 comments:

Unknown said...

Nice! Saved me some good time figuring out how to do it... this post is greatly appreciated!

Mike Wilson said...

The files have moved to my Drupal site. Please visit http://projects.babblemind.com/node/28 for the downloads.

Anonymous said...

Thanks a lot!

Anonymous said...

Works perfectly! Thanks for posting.

Mike Wilson said...

The files have moved again -- now at http://whisperingwind.co.uk/projects/sites/default/files/shortcut-buttons-src-0.1.jar

Gonzo said...

JButton button = new JButton("Test me!");
button.setMnemonic('T');

another possibility i guess

Anonymous said...

Thank you very much!

Anonymous said...

class OyenteAceptar implements ActionListener, KeyListener
{
public void actionPerformed(ActionEvent e)
{anyFunction();}

public void keyPressed(KeyEvent e)
{int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
anyFunction();
}
}