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

查看:35
本文介绍了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 教程.然后你可以使用 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天全站免登陆