Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I detect arrow keys in java?

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.

like image 234
Zeveso Avatar asked Dec 23 '10 20:12

Zeveso


People also ask

How do you tell which arrow key is which?

Alternatively referred to as cursor keys, direction keys, and navigation keys, the arrow keys are usually located between the standard section and the numeric pad on computer keyboards. It is made up of four keys: the left arrow (back arrow), up arrow, down arrow, and the right arrow (forward arrow).

What are the arrow keys called in Java?

The variables VK_UP , VK_DOWN , VK_LEFT , and VK_RIGHT represent the up, down, left, and right arrow key values respectively.


2 Answers

Use the getKeyCode() method and compare the returned value agains KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP and KeyEvent.VK_DOWN constants.

like image 150
Progman Avatar answered Oct 01 '22 23:10

Progman


Here is what I did to make it work:

public void keyPressed (KeyEvent e) {
        int c = e.getKeyCode ();
        if (c==KeyEvent.VK_UP) {                
            b.y--;   
        } else if(c==KeyEvent.VK_DOWN) {                
            b.y++;   
        } else if(c==KeyEvent.VK_LEFT) {                
            b.x--;   
        } else if(c==KeyEvent.VK_RIGHT) {                
            b.x++;   
        }
        System.out.println (b.x);
        b.repaint ();
    }

For me it isn't working if I put it in KeyPressed but works fine if I put it in KeyTyped.

like image 27
Abhas Tandon Avatar answered Oct 02 '22 00:10

Abhas Tandon