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

2024-03-12

In the following program, why does hitting the a key print "hello, world" while hitting CTRL+a doesn't?

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+a works as well?


我发现它更容易使用:

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

or:

KeyStroke controlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java Swing KeyStrokes:如何使 CTRL 修饰符起作用 的相关文章

随机推荐