MouseListener/KeyListener not working (JPanel)

前端 未结 3 2050
花落未央
花落未央 2020-12-18 07:38

I\'m doing a little project that involves the mouse and key listeners in JPanel. Unfortunately, none of the methods are called when I use the mouse/keyboard. I have worked

3条回答
  •  鱼传尺愫
    2020-12-18 08:27

    Have a look at Java KeyListener for JFrame is being unresponsive?.

    You need to register your KeyListener and MouseListener for every JComponent you want to listen to:

    public Hello() {
        addKeyListener(this);
        addMouseListener(this);
        panel.addKeyListener(this);
        panel.addMouseListener(this);
        frame.addKeyListener(this);
        frame.addMouseListener(this);
    }
    

    Edit:
    Key and mouse events are only fired from the JComponent which has focus at the time. Because of this there seems to be a consensus that KeyBindings may be favorable to KeyListeners. The two have their applications, however, and so there is no hard and fast rule here. Have a read of 'How to Write a Key Listener' and 'How to Write a Key Binding' and you'll get the gist.

提交回复
热议问题