JButton keyboard shortcuts

I have two JButton

, and I would like them to be used by the keyboard arrow keys whenever there is focus JFrame

.

Can anyone point me in the right direction?

+2


a source to share


3 answers


Changed from Swing Action version .

Initializing 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));

      



Act:

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);
    }
}

      

+3


a source


To intercept the keys (without worrying if a particular component has focus) you should use InputMap

. For example, read:

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

And go to constant WHEN_IN_FOCUSED_WINDOW

.



If the given button just doesn't name one method, the best way to do "what the button does" is:

SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
        ((AbstractButton) c).doClick();
    }
});

      

+2


a source


Okay, when you say you want to allow them to use the "arrow keys", I assume you want to be able to move focus. If so, read the section from the Swing manual on How to use the focus subsystem . He gives an example of how you can use the Enter key for this.

0


a source







All Articles