Java Swing KeyStrokes:如何使CTRL修饰符工作
在下面的程序中,为什么在按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); } }
我怎么能解决CTRL + a的问题呢?
我发现它更容易使用:
KeyStroke a = KeyStroke.getKeyStroke("A"); KeyStroke controlA = KeyStroke.getKeyStroke("control A");
要么:
KeyStroke controlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);
伙计,用这个
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK), "foo");
是的,上面的代码将起作用。
大图 – Ctrl + a和a被读作不同的击键, a和b将是不同的。