views:

192

answers:

3

Hello,

I have two JButtons and I would like to allow them to be used by the Arrow keys whenever the JFrame is in focus,

Can anyone point me in the right direction about this?

Thanks

~ Kyle

A: 

To intercept the keys (without worrying if the specific component is in focus) you should use the InputMap. Read up on for instance:

http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

And go for the WHEN_IN_FOCUSED_WINDOW constant.

Unless the button in question simply calls a single method, the best way to do "what ever the button does" is to do:

SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
        ((AbstractButton) c).doClick();
    }
});
aioobe
+2  A: 

Modified from Swing's Action demo.

The initialization of your button:

// Sets the mnemonic to down, with no hint display
JButton down = new JButton(new DownAction("Down", null, "This is the down button", new Integer(KeyEvent.VK_DOWN));

The action:

class DownAction extends AbstractAction {
    public DownAction(String text, ImageIcon icon,
                  String desc, Integer mnemonic) {
        super(text, icon);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
    }
    public void actionPerformed(ActionEvent e) {
        displayResult("Action for first button/menu item", e);
    }
}
justkt
A: 

Well, when you say you want to allow them to use the "arrow keys", I assume you mean you want to be able to transfer focus. If this is the case then read the section from the Swing tutorial on How to Use the Focus Subsystem. It gives an example of how you can use the Enter key for this.

camickr