我正在尝试进行密钥绑定。我想生成一个KeyStroke,只有在控制键被按下时才会执行操作。我不明白我做错了什么我使用相同的技术进行其他键绑定(Control + up,Control + down,up,c,p和其他按钮),我尝试过使用CTRL_DOWN_MASK,CTRL_MASK ,VK_CONTROL和“CONTROL”,但这些似乎都不起作用。我知道它不是我绑定它的方法,因为当我有两个其他键绑定到该操作(Control + Z)时,它工作但我想将它绑定到(Control)这里是我正在使用的代码。如果可以,请帮忙。
InputMap imap = leftPanel.getInputMap(mapName);
KeyStroke leftArrowKey = KeyStroke.getKeyStroke("LEFT");
imap.put(leftArrowKey, "left");
KeyStroke rightArrowKey = KeyStroke.getKeyStroke("RIGHT");
imap.put(rightArrowKey, "right");
KeyStroke upArrowKey = KeyStroke.getKeyStroke("UP");
imap.put(upArrowKey, "up");
KeyStroke cKey = KeyStroke.getKeyStroke('c');
imap.put(cKey, "c");
KeyStroke spaceKey = KeyStroke.getKeyStroke("SPACE");
imap.put(spaceKey, "space");
KeyStroke zoomInKeys = KeyStroke.getKeyStroke(VK_DOWN, CTRL_DOWN_MASK);
imap.put(zoomInKeys, "zoomin");
KeyStroke zoomOutKeys = KeyStroke.getKeyStroke(VK_UP, CTRL_DOWN_MASK);
imap.put(zoomOutKeys, "zoomout");
KeyStroke panKeys = KeyStroke.getKeyStroke("CONTROL");
imap.put(panKeys, "pan");
ActionMap amap = leftPanel.getActionMap();
amap.put("left", moveLeft);
amap.put("right", moveRight);
amap.put("up", increaseSpeed);
amap.put("c", changePaddleMode);
amap.put("space", nextBall);
amap.put("zoomin", zoomIn);
amap.put("zoomout", zoomOut);
amap.put("pan", pan);
问题在最后一个KeyStroke(panKeys)中弹出我不知道在getKeyStroke()方法中放入什么会使它响应被按下的控制键。
答案 0 :(得分:2)
这似乎对我有用:
public static void main(String[] args) {
JLabel label = new JLabel("Foo");
int condition = JLabel.WHEN_IN_FOCUSED_WINDOW;
InputMap inputmap = label.getInputMap(condition);
ActionMap actionmap = label.getActionMap();
// first to test that this works.
final String xKeyPressed = "x key pressed";
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, 0), xKeyPressed );
actionmap.put(xKeyPressed, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(xKeyPressed);
}
});
// Next to try it with just the control key
final String controlKeyPressed = "control key pressed";
inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL,
KeyEvent.CTRL_DOWN_MASK), controlKeyPressed );
actionmap.put(controlKeyPressed, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(controlKeyPressed);
}
});
JOptionPane.showMessageDialog(null, label);
}