MouseListener/KeyListener not working (JPanel)

寵の児 提交于 2019-11-29 08:19:39
Sean Connolly

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.

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.

Try this instead:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!