MouseListener/KeyListener not working (JPanel)

前端 未结 3 2047
花落未央
花落未央 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:10

    Try this instead:

     panel.addKeyListener(this);
     panel.addMouseListener(this);
    

    You have to add the listeners to every component you want to listen to.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-18 08:30

    Better to avoid using KeyListeners with JPanel, use KeyBindings instead. JPanel cannot gain focus so cannot interact with KeyEvents. Using KeyBindings, you can map an Action to a KeyStroke even when a component doesn't have focus.

    0 讨论(0)
提交回复
热议问题