JPanel not responding to KeyListener event

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

 public class HelloWorld extends JPanel implements KeyListener 

I am adding a HelloWorld object to the frame - app.add(helloWorld); . Now, when I press any keyboard key, the KeyListener methods are not KeyListener , and it seems that HelloWorld has no window focus. I also tried calling helloWorld.requestFocusInWindow(); but still didn’t answer.

How can I make it respond to a keystroke?

+6
source share
3 answers

Have you determined that the KeyListener for your HelloWorld panel will be the panel itself? In addition, you probably need to customize the panel. I tested it with 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(); } } 
+11
source

JPanel is not configured by default. That is, he cannot respond to events related to the focus, which means that he cannot respond to key events.

I would suggest trying to set Focus on the panel to true and try again. Make sure you press the panel first to make sure it gets focus.

Understand, however, you will get strange problems with focus traversal, since the panel will now receive input focus when the user moves through your forms, and it seems that the focus has been lost somewhere.

In addition, KeyListener tends to be unreliable in a similar situation (due to the focus manager working).

+8
source

just you have to add

 addKeylistener(new HelloWorld()); 
0
source

Source: https://habr.com/ru/post/920502/


All Articles