Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Catch KeyDown events for modifier keys

843807Sep 4 2010 — edited Sep 4 2010
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 2 2010
Added on Sep 4 2010
0 comments
927 views