3

I need a keylistener to be always 'listening' for the escape key to be pressed, to then exit the program.

I have tried typing addKeyListener(this); in my main constructor (the one with the panel being drawn in) and have used

public void keyPressed( KeyEvent e)

{
      int code = e.getKeyCode();
      if(code == KeyEvent.VK_ESCAPE)
      {
           System.exit( 0 );
      }


}

I get no errors, but pressing the escape key doesn't seem to do anything, any suggestions?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Mikeymca
  • 33
  • 1
  • 6

3 Answers3

2
  • Top-Level Container by default never receiving KeyEvent from KeyListener, by default, but is possible with a few code lines, wrong idea, wrong listener

  • JPanel by defaul react to KeyEvent, but only in the case that isFocusable, is FocusOwner, wrong idea, wrong listener, (for example) because you needed to move Focus from JTextField to JPanel programatically, wrong idea

  • add KeyBindings to JFrame/ JDialog / JWindow, accesible by default for Swing JComponent, not for AWT Components

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks for your help, I set the focus to the panel using requestFocusInWindow(); and assigned the keylistner to the panel directly – Mikeymca Mar 12 '13 at 13:05
  • hmmmm see clear, simple, [but great workaround Escape Key and Dialog](http://tips4java.wordpress.com/2010/10/17/escape-key-and-dialog/) by @camickr – mKorbel Mar 12 '13 at 13:35
1

You can use the InputMap/ActionMap mechanism :

    Object escapeActionKey = new Object();
    pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), escapeActionKey);
    pnl.getActionMap().put(escapeActionKey, new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.err.println("escape 1");
        }
    });

JComponent.WHEN_IN_FOCUSED_WINDOW means that this keystroke is available when the pnl component is in the focused window.

Or you can also add a global AWTEventListener listener :

    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
        public void eventDispatched(AWTEvent event) {
            if(event.getID() == KeyEvent.KEY_PRESSED) {
                KeyEvent kEvent = (KeyEvent) event;
                boolean isEsc = (kEvent.getKeyCode() == KeyEvent.VK_ESCAPE);
                if(isEsc) {
                    System.err.println("escape 2");
                }
            }
        }
    }, AWTEvent.KEY_EVENT_MASK);
barjak
  • 10,842
  • 3
  • 33
  • 47
0

In Swing there is a top layer panel : the GlassPane which allow to handle event at top level (to avoid other widget to comsume the event)

Gab
  • 7,869
  • 4
  • 37
  • 68