KeyListener works in Applet but not in JApplet

Following scenario: A simple Applet implementing the KeyListener <code> public class AppletMain extends Applet implements KeyListener{ } </code> Therefore you have to override following methods: <code> public void keyPressed(KeyEvent k) { } public void keyReleased(KeyEvent k) { } public void keyTyped(KeyEvent k) { System.out.println("A key has been typed"); } </code> This works perfectly, unfortunatly if I change it to a JApplet the Keys are not recognized anymore
1 answer

Use KeyEventDispatcher for JApplet

As for the fact that KeyListener does not work for JApplet as it does for Applet you should use the KeyEventDispatcher interface.

public class AppletMain extends JApplet implements java.awt.KeyEventDispatcher

Furthermore you have to set the KeyboardFocusManager to the Panel


Afterwards override the dispatchKeyEvent function of the interface:

public boolean dispatchKeyEvent(KeyEvent e);

This allows you to catch the KeyEvents as it is done with KeyListener.