The problem is, most likely, the applet doesn't have keyboard focus. This is a common issue with KeyListener.
While you have set the applet as being focusable, it doesn't mean that the applet has keyboard focus.
You could try using requestFocusInWindow
, but this may not work as expected in applets. You could also add a MouseListener to the applet, so that when the user clicks on the applet, you would requestFocusInWindow
to ensure that the applet has keyboard focus
I would recommend, instead, if you have to develop an applet, you try using JApplet
. Instead of painting directly to the applet itself, I'd recommend that you use a custom component, say something like, JPanel
, and override its paintComponent
method instead.
Apart from providing flexibility in regards to the deployment of the component, it's also double buffered.
Don't forget to call super.paintXxx
Also, this would also allow you to use the key bindings API which has the ability to overcome many of the shot comings of the KeyListener
reflink: https://stackoverflow.com/questions/19339781/why-doesnt-the-keylistener-work
For receives key events on JPanel
you must set focus:
setFocusable(true);
requestFocus();
the JPanel
now has focus, so it receives key events
reflink: https://stackoverflow.com/questions/16530775/keylistener-not-working-for-jpanel
https://www.daniweb.com/programming/software-development/threads/384681/keylistener-not-working
- Call
super.paintComponent
(not related to you question, but will solve some issues later on) - Make the component "focusable" -
Component#setFocusable
- Use key bindings over
KeyListener
- Use
Component#requestFocusInWindow
overComponent#requestFocus
...
From the Java Docs
Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible
reflink: https://stackoverflow.com/questions/13354230/keylistener-not-working