设置应用程序范围的关键监听器

n00*_*13f 8 java swing keyboard-shortcuts

如何设置应用程序范围的键监听器(键盘快捷键),以便在按下组合键(例如Ctrl+ Shift+ T)时,在Java应用程序中调用某个操作.

我知道键盘快捷键可以设置JMenuBar菜单项,但在我的情况下,应用程序没有菜单栏.

Ada*_*ski 17

查看Java教程的How To Use Key Bindings部分.

您需要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");
Run Code Online (Sandbox Code Playgroud)

  • 没问题 - 如果你愿意,你可以接受我的解决方案!(我需要积分!)。 (2认同)