KeyListener如何检测组合键(例如,ALT + 1 + 1) [英] How can a KeyListener detect key combinations (e.g., ALT + 1 + 1)

查看:109
本文介绍了KeyListener如何检测组合键(例如,ALT + 1 + 1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让我的自定义 KeyListener 侦听 ALT 的组合(或 CTRL 就此而言)+多个其他密钥?

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

假设我有11个不同的操作我希望应用程序执行操作,具体取决于组合按下的键。 ALT + 0 - ALT + 9 显然不会造成任何问题,而对于 ALT + 1 + 0 (或ALT + 10,因为它可以在帮助文件或类似文件中描述)我无法在网络上(或在我脑海中)的任何地方找到一个好的解决方案。我不相信带有计时器的解决方案是唯一可能的方式。

Assume I have 11 different actions I want the application to do, depending on a combination of keys pressed. ALT + 0 - ALT + 9 obviously don't pose any problems, whereas for ALT + 1 + 0 (or "ALT+10" as it could be described in a Help file or similar) I cannot find a good solution anywhere on the web (or in my head). I'm not convinced that this solution with a timer is the only possible way.

提前一百万感谢任何建议!

Thanks a million in advance for any suggestions!

编辑:动作0-9 +动作10 = 11动作。谢谢@ X-Zero。

Actions 0-9 + action 10 = 11 actions. Thanks @X-Zero.

推荐答案

您不应该将KeyListener用于此类交互。而是使用键绑定,您可以在 Java Tutorial 。然后你可以使用 InputEvent 掩码表示何时删除各种修饰键。例如:

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

请参阅 KeyStroke ,了解您在获取KeyStroke时可以使用的不同代码。这些修饰符可以一起进行或运算,以表示各种键组合。例如

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)

表示何时 Ctrl + Shift 按键被按下。

编辑:正如已经指出的,这不能回答你问题,但应该只是作为一些好的建议。

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

这篇关于KeyListener如何检测组合键(例如,ALT + 1 + 1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆