andreikashin
andreikashin

Reputation: 1605

KeyListener does not react to keyboard event. Ok for mouse events

JPanel reacts very strange to events. It could process the MouseEvent, but won't handle KeyEvent.

JPanel class:

public class DrawPanel extends JPanel {
    class DrawListener extends MouseAdapter implements KeyListener {
        @Override
        public void mouseDragged(MouseEvent e) {
            // works fine
        }
        @Override
        public void mouseReleased(MouseEvent e) {       
            // works fine
        }
        @Override
        public void mouseClicked(MouseEvent e) {
            // works fine
        }
        @Override
        public void keyPressed(KeyEvent e) {
            // Listener is NOT invoked here if anykey is pressed
        }
        @Override
        public void keyReleased(KeyEvent e) {
            // NOT invoked 
        }
        @Override
        public void keyTyped(KeyEvent e) {
            // NOT invoked 
        }

Constructor for panel:

// Class constructor
public DrawPanel() {
        DrawListener l = new DrawListener();
        addMouseListener(l);
        addMouseMotionListener(l);
        addKeyListener(l);
        setFocusable(true);
        requestFocus();
}

How is it possible, if MouseEvent handler works just fine? Where it could be wrong?

Upvotes: 0

Views: 468

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347214

KeyListener will only respond to key events if the component it is registered to is focusable AND has keyboard focus.

This is a known issue with KeyListener.

The best choice is to make use the Key Bindings API which allows you to control the focus level that the key events will occur at.

Upvotes: 3

Related Questions