2010-04-28 237 views
2

我有两个JButton s,我希望允许他们使用键盘箭头键,只要JFrame有重点。JButton键盘快捷键

任何人都可以在正确的方向指向我吗?

回答

2

要拦截键(不用担心特定组件是否在焦点),应该使用InputMap。阅读上,例如:

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

,去了WHEN_IN_FOCUSED_WINDOW不变。

除非该按钮只需调用一个方法,做最好的办法“什么都该按钮并”是要做到:从Swing的Action演示修改

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

您的按钮的初始化:

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

行动:

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

那么,当你说你要允许他们使用“箭头键”,我假设你的意思是你希望能够转移焦点。如果是这种情况,请阅读Swing教程How to Use the Focus Subsystem中的部分。它给出了一个如何使用Enter键的例子。