I'm writing a simple program in Java which includes a KeyListener with the following overriding they KeyTyped method:
@Override
public void keyTyped(KeyEvent e)
{
int key = e.getKeyCode();
System.out.println("TEST");
if (key == KeyEvent.VK_KP_LEFT || key == KeyEvent.VK_LEFT)
{
System.out.println("LEFT");
//Call some function
}
else if (key == KeyEvent.VK_KP_RIGHT || key == KeyEvent.VK_RIGHT)
{
System.out.println("RIGHT");
//Call some function
}
}
When I type anything other than the arrow keys (e.g. "a"), it prints TEST
as it should. However, when I type a numpad arrowkey, it only prints TEST
and when I type a standard arrow key it doesn't print anything at all. Is this possibly because I'm on a laptop, or have I just made a silly mistake somewhere?
Yep, you'll see the arrow keys respond to keyPressed and keyReleased, not keyTyped. My SSCCE:
So to solve this, override keyPressed rather than keyTyped if you want to listen to arrow events.
Or for an even better solution: use Key Bindings
Edit
My Key Bindings version: