KeyListeners and TopComponents

Just like JPanels, TopComponents are not focusable by default. They need to be explicitly defined as such, as shown below. Then key listening works, though remember that the TopComponent needs to be the currently active TopComponent, otherwise some other TopComponent will catch your key events.

...
...
...
public final class DemoTopComponent extends TopComponent {

    public DemoTopComponent() {
        initComponents();
        setName(Bundle.CTL_DemoTopComponent());
        setToolTipText(Bundle.HINT_DemoTopComponent());
        setFocusable(true);
        addKeyListener(new MyKeyAdapter());
    }

    private class MyKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            int keycode = e.getKeyCode();
            switch (keycode) {
                case KeyEvent.VK_LEFT:
                    JOptionPane.showMessageDialog(null, "Left: " + e.getKeyCode());
                    break;
                case KeyEvent.VK_RIGHT:
                    JOptionPane.showMessageDialog(null, "Right: " + e.getKeyCode());
                    break;
                case KeyEvent.VK_DOWN:
                    JOptionPane.showMessageDialog(null, "Down: " + e.getKeyCode());
                    break;
                case KeyEvent.VK_UP:
                    JOptionPane.showMessageDialog(null, "Up: " + e.getKeyCode());
                    break;
            }
        }
    }

    ...
    ...
    ...

Helpful reference which caused me to see the light: http://stackoverflow.com/questions/3728035/java-tracking-keystrokes-with-inputmap

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
12
13
14
23
24
25
26
27
28
29
30
   
       
Today