Setting up application wide Key Listeners

左心房为你撑大大i 提交于 2019-12-18 11:33:46

问题


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.

I know keyboard shortcuts can be set JMenuBar menu items, but in my case the application does not have a menu bar.


回答1:


Check out the How To Use Key Bindings section of the Java tutorial.

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 InputMaps. Given that you don't have a JMenuBar you could simply register the key bindings with a top-level JPanel in your application.

For example:

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");


来源:https://stackoverflow.com/questions/1231622/setting-up-application-wide-key-listeners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!