0

我正在尝试进行键绑定。我想生成一个 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() 方法中放入什么,以使其响应被按住的控制键。

4

1 回答 1

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);
}
于 2012-05-14T22:09:39.997 回答