Java Swing KeyStrokes:如何使 CTRL 修饰符起作用
在下面的程序中,为什么按下 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);
}
}
我该如何修复 CTRL+a 也能正常工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现使用以下方法更容易:
或:
I find it easier to use:
or:
哥们,用这个
Dude, use this
是的,上面的代码可以工作。
大图 - Ctrl+a 和 a 被读取为不同的击键,与 a 和 b 相同,会有所不同。
Yep, the above code will work.
Big picture - Ctrl+a and a are read as different keystrokes the same as a and b would be different.