How can a KeyListener detect key combinations (e.g., ALT + 1 + 1)

前端 未结 6 1329
悲哀的现实
悲哀的现实 2020-11-27 07:02

How can I let my custom KeyListener listen for combinations of ALT (or CTRL for that matter) + more than one other key?

Assume

6条回答
  •  离开以前
    2020-11-27 07:31

    You should not use KeyListener for this type of interaction. Instead use key bindings, which you can read about in the Java Tutorial. Then you can use the InputEvent mask to represent when the various modifier keys are depresed. For example:

    // Component that you want listening to your key
    JComponent component = ...;
    component.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
                                java.awt.event.InputEvent.CTRL_DOWN_MASK),
                        "actionMapKey");
    component.getActionMap().put("actionMapKey",
                         someAction);
    

    See the javadoc for KeyStroke for the different codes you can use while getting the KeyStroke. These modifiers can be OR'ed together to represent various combinations of keys. Such as

    KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
                           java.awt.event.InputEvent.CTRL_DOWN_MASK
                           | java.awt.event.InputEvent.SHIFT_DOWN_MASK)
    

    To represent when the Ctrl + Shift keys were depressed.

    Edit: As has been pointed out, this does not answer you question but instead should just be taken as some good advice.

提交回复
热议问题