Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

events

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!

like image 719
Ali Avatar asked Mar 05 '09 22:03

Ali


People also ask

How do you check if a specific key is pressed in Java?

Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.

How do I know which arrow key to press?

Conclusion. We can detect arrow key presses by listening to the keydown event. And in the event listener, we can either check the key or keydown properties of the event object to see which key is pressed. And there you have it.

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.

What does keyPressed do in Java?

In Java, there are three types of KeyEvent. The types correspond to pressing a key, releasing a key, and typing a character. The keyPressed method is called when the user presses a key, the keyReleased method is called when the user releases a key, and the keyTyped method is called when the user types a character.


1 Answers

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;      } }  
like image 107
OscarRyz Avatar answered Sep 24 '22 06:09

OscarRyz