KeyListener 如何检测组合键(例如 ALT + 1 + 1)

发布于 2024-12-11 03:32:02 字数 480 浏览 0 评论 0原文

如何让我的自定义 KeyListener 监听 ALT(或 CTRL)+多个其他键的组合?

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

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

编辑:操作 0-9 + 操作 10 = 11 个操作。谢谢@X-零。

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

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!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

说不完的你爱 2024-12-18 03:32:02

您不应该使用 KeyListener 进行此类交互。请改用键绑定,您可以在 Java 教程。然后您可以使用 InputEvent 掩码表示何时按下各个修饰键。例如:

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

请参阅 javadoc 中的 KeyStroke 获取 KeyStroke 时可以使用的不同代码。这些修饰符可以通过 OR 组合在一起来表示各种按键组合。例如

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

To 表示按下 Ctrl + Shift 键的时间。

编辑:正如已经指出的,这并不能回答您的问题,而应该被视为一些好的建议。

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.

遇到 2024-12-18 03:32:02

您可以通过组合某些东西来使用KeyListener来达到此目的。请看以下示例,该示例应放置在重写的 keyPressed(KeyEvent e) 方法中。

if (e.isControlDown() && e.getKeyChar() != 'a' && e.getKeyCode() == 65) {
        System.out.println("Select All"); 
}

当按下 Ctrl + a 时,将显示字符串 Select Alle.isControlDown() 方法检查 Ctrl 键是否被按下。
类似地,可以使用 e.isAltDown() 方法以相同的方法完成 Alt 组合键。

其背后的逻辑是,e.getKeyChar() 返回按键的字符 & e.getKeyCode() 返回其 ASCII 代码。当按住 Ctrl 时,e.getKeyChar() 不会返回 ae.getKeyCode() 将是相同的 65。希望你明白这一点。请随时询问更多信息。

You can use KeyListener for this purpose by combining certain things. Look at the following example, which should be placed in an overridden keyPressed(KeyEvent e) method.

if (e.isControlDown() && e.getKeyChar() != 'a' && e.getKeyCode() == 65) {
        System.out.println("Select All"); 
}

The string Select All will be displayed when Ctrl + a is pressed. The method e.isControlDown() checks whether the Ctrl key is pressed or not.
Similarly, the Alt key combinations can be done with the same method by using e.isAltDown() method.

The logic behind this is, e.getKeyChar() returns the character of the key presses & e.getKeyCode() returns its ASCII code. When Ctrl is pressed and hold, the e.getKeyChar() won't return a and e.getKeyCode() will be the same 65. Hope you understand this. Feel free to ask more.

酒废 2024-12-18 03:32:02

ALT + 1 + 0(或“ALT+10”,因为它可以在帮助文件或类似文件中描述)

似乎与(来自您的评论之一)冲突:

例如,如果用户想要更改第 11 列(称为“10”)中的数据,他/她可以按 ALT + 1 + [同时松开 ALT 和 1] 0。

假设 ALT+10 意味着'按下 ALT,按下并释放 1,按下并释放 0,释放 ALT' 我建议尝试这样做:

在 keyPressed 中,监听 ALT 键,激活布尔标志 isAltPressed,并且创建一个缓冲区来保存发生的按键(例如,一个字符串)。
在 keyTyped 中,如果 isAltPressed 处于活动状态,则将键代码附加到缓冲区。
在 keyReleased 中,再次监听 ALT,打开条件查询缓冲区并执行操作。

    public void keyPressed (KeyEvent e){
        if (e.getKeyCode() == KeyEvent.VK_ALT){
        buffer = ""; //declared globally
        isAltPressed = true; } //declared globally
    }

    public void keyTyped (KeyEvent e){
        if (isAltPressed)
            buffer.append (e.getKeyChar());
    }

    public void keyReleased (KeyEvent e){
        if (e.getKeyCode() == KeyEvent.VK_ALT){
            isAltPressed = false;
            if (buffer.equals (4948)) //for pressing "1" and then "0"
                doAction();
            else if (buffer.equals(...))
                doOtherAction();
            ...
        }//if alt
    }

ALT + 1 + 0 (or "ALT+10" as it could be described in a Help file or similar)

seems to clash with (from one of your comments):

So for example if the user wants to change data in column 11 (which would be called "10"), s/he'd press ALT + 1 + [lets go of both ALT and 1] 0.

Assuming that ALT+10 means 'Pressing ALT, pressing and releasing 1, pressing and releasing 0, releasing ALT' I propose trying this:

In keyPressed, listening for the ALT key, activate a boolean flag, isAltPressed, and create a buffer to hold key presses that occur (a string, say).
In keyTyped, if isAltPressed is active, append key codes to the buffer.
In keyReleased, listening for ALT again, open a conditional querying the buffer and executing actions.

    public void keyPressed (KeyEvent e){
        if (e.getKeyCode() == KeyEvent.VK_ALT){
        buffer = ""; //declared globally
        isAltPressed = true; } //declared globally
    }

    public void keyTyped (KeyEvent e){
        if (isAltPressed)
            buffer.append (e.getKeyChar());
    }

    public void keyReleased (KeyEvent e){
        if (e.getKeyCode() == KeyEvent.VK_ALT){
            isAltPressed = false;
            if (buffer.equals (4948)) //for pressing "1" and then "0"
                doAction();
            else if (buffer.equals(...))
                doOtherAction();
            ...
        }//if alt
    }
南风起 2024-12-18 03:32:02
import java.awt.*;
import java.awt.event.*;
class KDemo
{
     public static void main(String args[])
     {
           Frame f = new Frame();
           f.setSize(500,500);
           f.setVisible(true);
           f.addKeyListener(new KeyAdapter()
           {
               public void keyPressed(KeyEvent e)
               {
                   AWTKeyStroke ak = AWTKeyStroke.getAWTKeyStrokeForEvent(e);
                   if(ak.equals(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_F4,InputEvent.ALT_MASK)))
                   {
                     System.exit(0);
                   }
               }
           });
        }
   }
import java.awt.*;
import java.awt.event.*;
class KDemo
{
     public static void main(String args[])
     {
           Frame f = new Frame();
           f.setSize(500,500);
           f.setVisible(true);
           f.addKeyListener(new KeyAdapter()
           {
               public void keyPressed(KeyEvent e)
               {
                   AWTKeyStroke ak = AWTKeyStroke.getAWTKeyStrokeForEvent(e);
                   if(ak.equals(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_F4,InputEvent.ALT_MASK)))
                   {
                     System.exit(0);
                   }
               }
           });
        }
   }
铃予 2024-12-18 03:32:02

我建议不要使用组合键,而是在窗口 isVisible() 并获得焦点时考虑一些输入字段。该字段可以是隐藏的,如 Windows 的文件资源管理器隐藏文件名搜索(输入目录,键入文件名,对应的内容将被聚焦),也可以是可见的,如在 Ubuntu 中。

组合键的设计目的不是为了包含除修饰符之外的多个键,尽管您也许能够实现这一点。

I would suggest that instead of using key combinations, consider some input field when the window isVisible() and is focused. The field can be hidden, like Windows' File explorer hidden filename search (enter a directory, type the filename and the correspondence is focused), or is visible, like in Ubuntu.

Key combinations are not designed for including more than one key other than modifiers, although you may be able to achieve this.

清眉祭 2024-12-18 03:32:02

我认为我正在使用一种更简单的方法。如果 KeyEvent 为 ev,那么如果您进行调查:

(int)ev.getKeyChar()

您会发现 ctrl-a 为 1,ctrl-b是 2 等等。我想使用 ctrl-s 进行保存。所以我只是使用:

(((int)ev.getKeyChar())==19)

来检测它。不知道为什么,但它工作得很好,而:

ev.isControlDown() && ev.getKeyChar()=='s'

却不行。

I think there's a simpler way which I am using. If the KeyEvent is ev then if you investigate:

(int)ev.getKeyChar()

you find that ctrl-a is 1, ctrl-b is 2 and so on. I wanted to use ctrl-s for save. So I just use:

(((int)ev.getKeyChar())==19)

to detect it. No idea why, but it works fine whereas:

ev.isControlDown() && ev.getKeyChar()=='s'

does not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文