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:
Nice! Saved me some good time figuring out how to do it... this post is greatly appreciated!
The files have moved to my Drupal site. Please visit http://projects.babblemind.com/node/28 for the downloads.
Thanks a lot!
Works perfectly! Thanks for posting.
The files have moved again -- now at http://whisperingwind.co.uk/projects/sites/default/files/shortcut-buttons-src-0.1.jar
JButton button = new JButton("Test me!");
button.setMnemonic('T');
another possibility i guess
Thank you very much!
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();
}
}
Post a Comment