我如何设置应用程序范围的按键侦听器(键盘快捷键),以便在按下组合键(例如Ctrl+ Shift+ T)时,将在Java应用程序中调用特定的操作。
我知道可以设置JMenuBar
菜单项的键盘快捷键,但就我而言,该应用程序没有菜单栏。
查看Java教程的“ 如何使用键绑定”部分。
您需要Action
在组件的一个中创建并注册一个,ActionMap
并在应用程序的一个组件中注册一个(KeyStroke
,Action Name)对InputMap
。假设您没有,则JMenuBar
只需JPanel
在应用程序的顶级注册键绑定。
例如:
Action action = new AbstractAction("Do It") { ... };
// This is the component we will register the keyboard shortcut with.
JPanel pnl = new JPanel();
// Create KeyStroke that will be used to invoke the action.
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK);
// Register Action in component's ActionMap.
pnl.getActionMap().put("Do It", action);
// Now register KeyStroke used to fire the action. I am registering this with the
// InputMap used when the component's parent window has focus.
pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "Do It");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句