Java - Detecting any key press with KeyBindings?

2019-07-17 15:57发布

I read that it is better to use KeyBindings than KeyListeners. I see how KeyBindings are useful for a specific reaction to a specific key; but I am also trying to detect the press/release of ANY key on the keyboard: is there a way to do this with KeyBindings?

For example, I would use KeyBindings normally to act on a single key as so:

InputMap iMap = component.getInputMap();
ActionMap aMap = component.getActionMap();

iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter without modifiers");
aMap.put("enter without modifiers", new AbstractAction(){
      public void actionPerformed(ActionEvent a){
              System.out.println("Enter pressed alone");
      });

So I am thinking something like this for detecting any key press:

iMap.put(KeyStroke.getKeyStroke(KeyEvent.KEY_PRESSED, 0), "any key was pressed");
aMap.put("any key was pressed", new AbstractAction(){
      public void actionPerformed(ActionEvent a){
              System.out.println("some key was pressed, regardless of which key...");
      });

Is there a way to accomplish this?

Also, is there a way to catch they KeyBinding with ANY modifiers combination? E.g. to have the Enter-action mapped regardless of if no modifiers are held, or if both ctrl-alt etc. in any combination are held?

Thanks very much, Dan

Cross-posted on: http://www.javaprogrammingforums.com/whats-wrong-my-code/26194-how-detect-any-key-press-keybindings.html#post103862

1条回答
Juvenile、少年°
2楼-- · 2019-07-17 16:27

I see how KeyBindings are useful for a specific reaction to a specific key;

Yes, that is when you would use key bindings

but I am also trying to detect the press/release of ANY key on the keyboard: is there a way to do this with KeyBindings?

No, key bindings is not used for this purpose.

Also, is there a way to catch they KeyBinding with ANY modifiers combination?

No, again bindings are for a specific KeyStroke. So you would need to write a method to add bindings for each combination. Note that order doesn't matter. That is Shift+Alt is the same as Alt+Shift

In most cases Key Bindings is the preferred approach. In your case it is not.

A KeyListener may be appropriate if you are listening for KeyEvents on a specific component that has focus.

Or it you want to listen for KeyEvents on a more global basis then you can take a look at Global Event Listeners or maybe Global Event Dispatching depending on your exact requirement.

查看更多
登录 后发表回答