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

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

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

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

您需要在组件的ActionMap创建并注册Action ,并在应用程序组件的InputMap注册一个( KeyStrokeAction Name )对。 鉴于您没有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");