开发者

JButton keyboard shortcuts

开发者 https://www.devze.com 2022-12-28 05:53 出处:网络
I have two JButtons and I would like to allow them to be used by the keyboard arrow keys whenever the JFrame has the focus.

I have two JButtons and I would like to allow them to be used by the keyboard arrow keys whenever the JFrame has the focus.

Can anyone point me in the right direction a开发者_如何学JAVAbout this?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消