设置应用程序范围的关键监听器 [英] Setting up application wide Key Listeners
问题描述
如何设置应用程序范围的键侦听器(键盘快捷键),以便在键组合时(例如 Ctrl + Shift + T 按下,在Java应用程序中调用某个动作。
How do i setup application wide key listeners (keyboard shortcuts), so that when a key combination (e.g. Ctrl + Shift + T) is pressed, a certain action is invoked in a Java application.
我知道键盘快捷键可以设置 JMenuBar
菜单项,但在我的情况下,应用程序没有菜单栏。
I know keyboard shortcuts can be set JMenuBar
menu items, but in my case the application does not have a menu bar.
推荐答案
查看如何使用密钥绑定的Java教程。
您需要使用组件的 ActionMap
创建并注册 Action
并注册a ( KeyStroke
,动作名称)对应用程序的某个组件的 InputMap
。鉴于你没有 JMenuBar
,你只需在你的顶级 JPanel
中注册密钥绑定即可。应用。
You need to create and register an Action
with your component's ActionMap
and the register a (KeyStroke
, Action Name) pair in one of your application's component's InputMap
s. Given that you don't have a JMenuBar
you could simply register the key bindings with a top-level JPanel
in your application.
例如:
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");
这篇关于设置应用程序范围的关键监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!