Tom*_*ine 39
对于每个窗口,使用JComponent.registerKeyboardAction
条件为WHEN_IN_FOCUSED_WINDOW
.或者使用:
JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, command);
JComponent.getActionMap().put(command,action);
Run Code Online (Sandbox Code Playgroud)
如registerKeyboardAction API文档中所述.
dan*_*ann 14
对于想知道(像我一样)如何使用KeyEventDispatcher的人来说,这是我放在一起的一个例子.它使用HashMap存储所有全局操作,因为我不喜欢大型if (key == ..) then .. else if (key == ..) then .. else if (key ==..) ..
构造.
/** map containing all global actions */
private HashMap<KeyStroke, Action> actionMap = new HashMap<KeyStroke, Action>();
/** call this somewhere in your GUI construction */
private void setup() {
KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK);
actionMap.put(key1, new AbstractAction("action1") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Ctrl-A pressed: " + e);
}
});
// add more actions..
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.addKeyEventDispatcher( new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
if ( actionMap.containsKey(keyStroke) ) {
final Action a = actionMap.get(keyStroke);
final ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), null );
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
a.actionPerformed(ae);
}
} );
return true;
}
return false;
}
});
}
Run Code Online (Sandbox Code Playgroud)
可能没有必要使用SwingUtils.invokeLater(),但最好不要阻止全局事件循环.
当您有菜单时,可以向菜单项添加全局键盘快捷键:
JMenuItem item = new JMenuItem(action);
KeyStroke key = KeyStroke.getKeyStroke(
KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK);
item.setAccelerator(key);
menu.add(item);
Run Code Online (Sandbox Code Playgroud)