我有两个JButton
s ,我想让它们在JFrame
获得焦点时被键盘箭头键使用。
谁能指出我正确的方向?
修改自 Swing 的动作演示。
按钮的初始化:
// 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);
}
}
要拦截键(不用担心特定组件是否处于焦点),您应该使用InputMap
. 阅读例如:
http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
并追求WHEN_IN_FOCUSED_WINDOW
常数。
除非有问题的按钮只调用一个方法,否则“按钮所做的一切”的最佳方法是:
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
((AbstractButton) c).doClick();
}
});
好吧,当您说要允许他们使用“箭头键”时,我假设您的意思是您希望能够转移焦点。如果是这种情况,请阅读 Swing 教程中有关如何使用焦点子系统的部分。它提供了一个示例,说明如何为此使用 Enter 键。