Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...