javaswingnetbeanskeylistener

JPanel doesn't response to KeyListener event


I have a subclass of JFrame that uses a class extended from JPanel

public class HelloWorld extends JPanel implements KeyListener

I add an object of HelloWorld to the frame - app.add(helloWorld);. Now, when I press any keyboard key non of the KeyListener methods gets called and it seems that helloWorld doesn't have window focus. I have tried also to invoke helloWorld.requestFocusInWindow(); but still doesn't respond.

How can I make it respond to key press?


Solution

  • Did you set that KeyListener for your HelloWorld panel would be that panel itself? Also you probably need to set that panel focusable. I tested it by this code and it seems to work as it should

    class HelloWorld extends JPanel implements KeyListener{
        public void keyTyped(KeyEvent e) {
            System.out.println("keyTyped: "+e);
        }
        public void keyPressed(KeyEvent e) {
            System.out.println("keyPressed: "+e);
        }
        public void keyReleased(KeyEvent e) {
            System.out.println("keyReleased: "+e);
        }
    }
    
    class MyFrame extends JFrame {
        public MyFrame() {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(200,200);
    
            HelloWorld helloWorld=new HelloWorld();
    
            helloWorld.addKeyListener(helloWorld);
            helloWorld.setFocusable(true);
    
            add(helloWorld);
            setVisible(true);
        }
        public static void main(String[] args) {
            new MyFrame();
        }
    }