I need to be able to tell when a user presses or releases the CTRL key for my application, but I can't get KeyListeners to work and the key bindings only appear to work with releasing the key. I also have key bindings for CTRL key combinations (like CTRL-N, CTRL-S, etc.), but I need an event which is fired when the user first presses the CTRL key. The goal is to have a tooltip on my custom JPanel which pops up when I press CTRL and goes away when I release it.
My (broken) key binding code:
JPanel main=new JPanel();
InputMap im=main.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke("pressed CONTROL"), "cDown");
im.put(KeyStroke.getKeyStroke("released CONTROL"), "cUp");
main.getActionMap().put("cDown",new AbstractAction() {
public void actionPerformed(ActionEvent e) {
isCtrlDown=true;
updateTooltip();
System.out.println("down");
}
});
main.getActionMap().put("cUp",new AbstractAction() {
public void actionPerformed(ActionEvent e) {
isCtrlDown=false;
updateTooltip();
System.out.println("up");
}
});
If you press the control key a few times over this component, you only get "up" printed.