This site is currently read-only as we are migrating to Oracle Forums for an improved community experience. You will not be able to initiate activity until January 31st, when you will be able to use this site as normal.

    Forum Stats

  • 3,890,899 Users
  • 2,269,649 Discussions


Catch KeyDown events for modifier keys

843807 Member Posts: 46,582
edited Sep 4, 2010 9:20AM in Abstract Window Toolkit (AWT)
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) {
main.getActionMap().put("cUp",new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
If you press the control key a few times over this component, you only get "up" printed.
This discussion has been closed.