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
Try this instead:
panel.addKeyListener(this);
panel.addMouseListener(this);
You have to add the listeners to every component you want to listen to.
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.