Java Swing KeyStrokes:如何使CTRL修饰符工作 [英] Java Swing KeyStrokes: how to make CTRL-modifier work
本文介绍了Java Swing KeyStrokes:如何使CTRL修饰符工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的程序中,为什么在按下 CTRL + a <时按 a 键打印hello,world / kbd>不?
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);
}
}
如何修复 CTRL + a 也适用?
How could I fix it that CTRL+a works as well?
推荐答案
我发现它更容易使用:
KeyStroke a = KeyStroke.getKeyStroke("A");
KeyStroke controlA = KeyStroke.getKeyStroke("control A");
或:
KeyStroke controlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);
这篇关于Java Swing KeyStrokes:如何使CTRL修饰符工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文