I’m trying to do key binding. I want to generate a KeyStroke that would preform an action if an only if the control key is being held down. I don’t understand what I’m doing wrong i’m using the same technique for my other key bindings (Control+up, Control+down, up, c, p and other buttons), I’ve tried using CTRL_DOWN_MASK, CTRL_MASK, VK_CONTROL, and “CONTROL” but none of those seem to work. I know its not the method I’m binding it to because It works when I have two other keys bonded to that action (Control+Z) but I want to just bind it to (Control) here is the code I’m using. Please help if you can.
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);
The problem pops up in the last KeyStroke (panKeys) I don’t know what to put in the getKeyStroke() method that would make it respond to the control key being held down.
This seemed to work for me:
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);
}