Java Swing KeyStrokes:如何使 CTRL 修饰符起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2419608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:22:23  来源:igfitidea点击:

Java Swing KeyStrokes: how to make CTRL-modifier work

javaswingactionkeystroke

提问by Thomas

In the following program, why does hitting the akey print "hello, world"while hitting CTRL+adoesn't?

在下面的程序中,为什么a按键打印“hello, world”而按CTRL+a不打印?

import java.awt.event.*;
import javax.swing.*;

public class KeyStrokeTest {
    public static void main(String[] args) {
        JPanel panel = new JPanel();

        /* add a new action named "foo" to the panel's action map */
        panel.getActionMap().put("foo", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("hello, world");
                }
            });

        /* connect two keystrokes with the newly created "foo" action:
           - a
           - CTRL-a
        */
        InputMap inputMap = panel.getInputMap();
        inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), 0), "foo");
        inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), InputEvent.CTRL_DOWN_MASK), "foo");

        /* display the panel in a frame */
        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }
}

How could I fix it that CTRL+aworks as well?

我怎样才能修复它,CTRL+ 也能a正常工作?

采纳答案by camickr

I find it easier to use:

我发现它更易于使用:

KeyStroke a = KeyStroke.getKeyStroke("A");
KeyStroke controlA = KeyStroke.getKeyStroke("control A");

or:

或者:

KeyStroke controlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);

回答by bragboy

Dude, use this

哥们,用这个

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK), "foo");

回答by SOA Nerd

Yep, the above code will work.

是的,上面的代码会起作用。

Big picture - Ctrl+aand aare read as different keystrokes the same as aand bwould be different.

大图 -Ctrl+aa被解读为不同的击键一样a并且b会有所不同。