tags:

views:

2560

answers:

5

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!

A: 

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());

Pooria
A: 

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?

TofuBeer
I just need to know what constant to use for checking this, right now i'm comparing with the numerical value of 39/37 etc.
Click Upvote
I don't think I would really call that refactoring...
TofuBeer
+2  A: 
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://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/KeyEvent.html

banjollity
final int code; code = e.getKeyCode(); switch(code) { } will be faster and just as clear.
TofuBeer
+1  A: 

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
    }
Jaime
+1 for making me laugh
Click Upvote
+4  A: 
public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch( keyCode ) { 
        case KeyEvent.VK_UP:
            // handle up 
            break;
        case KeyEvent.VK_DOWN:
            // handle down 
            break;
        case KeyEvent.VK_LEFT:
            // handle left
            break;
        case KeyEvent.VK_RIGHT :
            // handle right
            break;
     }
} 
OscarRyz
replace KeyEvet with KeyEvent :)
Ricket