JPanel doesn't response to KeyListener event

前端 未结 4 701
深忆病人
深忆病人 2020-12-06 18:28

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

public class HelloWorld extends JPanel implements KeyListener


        
相关标签:
4条回答
  • 2020-12-06 18:53

    add this in MyFrame method;

    this.addKeyListener(helloWorld);
    
    0 讨论(0)
  • 2020-12-06 19:10

    simple you have to add

    addKeylistener(new HelloWorld());
    
    0 讨论(0)
  • 2020-12-06 19:11

    JPanel is not Focusable by default. That is, it can not respond to focus related events, meaning that it can not respond to the keyevents.

    I would suggest trying to setFocusable on the pane to true and trying again. Make sure you click the panel first to make sure it receives focus.

    Understand though, you WILL get strange focus traversal issues, as the panel will now receive input focus as the user navigates through your forms, making it seem like the focus has been lost some where.

    Also, KeyListeners tend to be unreliable in this kind of situation (due to the way that the focus manager works).

    0 讨论(0)
  • 2020-12-06 19:14

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题