how can I detect arrow keys in java?

Zeveso picture Zeveso · Dec 23, 2010 · Viewed 89.9k times · Source

I know how to implement a key listener; that's not the problem.

public void keyTyped(KeyEvent event) {
    if (event.getKeyChar() == KEY_LEFT) {
        cTDirection = LEFT;
    }
    if (event.getKeyChar() == 40) {
        cTDirection = DOWN;
    }
    if (event.getKeyChar() == 39) {
        cTDirection = RIGHT;
    }
    if (event.getKeyChar() == 38) {
        cTDirection = UP;
    }
}

What do I put where the LEFT_KEY / 40 / 39 / 38? When I created a keylistener and type in the keys, I believe I got 37 - 40. I don't know what to put there to listen for just the arrow keys.

Answer

robert_x44 picture robert_x44 · Dec 23, 2010

I would recommend using:

if (event.getKeyCode() == KeyEvent.VK_UP) {
...
}

repeating with VK_DOWN, VK_LEFT, VK_RIGHT.

There are seperate codes for the numeric keypad: VK_KP_UP, VK_KP_DOWN, VK_KP_LEFT, VK_KP_RIGHT if you need them.

See KeyEvent for all of the codes.