[java] How to check if the key pressed was an arrow key in Java KeyListener?

Can you help me refactor this code:

public void keyPressed(KeyEvent e)
    {

    if (e.getKeyCode()==39)
    {
                //Right arrow key code
    }

    else if (e.getKeyCode()==37)
    {
                //Left arrow key code
    }

    repaint();

}

Please mention how to check for up/down arrow keys as well.Thanks!

This question is related to java events

The answer is


If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());


You should be using things like: KeyEvent.VK_UP instead of the actual code.

How are you wanting to refactor it? What is the goal of the refactoring?


public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html


Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:

    else if (e.getKeyCode()==38)
    {
            //Up arrow key code
    }
    else if (e.getKeyCode()==40)
    {
            //down arrow key code
    }