2009-08-05 43 views
8

怎样安装应用广泛的按键侦听(键盘快捷键),这样,当按下一个键组合(例如按Ctrl + + 牛逼),一定会调用操作在Java应用程序中。设置应用广泛的按键侦听

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

回答

17

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

您需要创建并注册您的组件的ActionMapAction和应用程序的组件InputMap S的一个注册(KeyStroke动作名称)对。鉴于您没有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"); 
+0

它的作品!谢谢。 – n002213f 2009-08-05 11:48:41