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.
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).
The variables VK_UP , VK_DOWN , VK_LEFT , and VK_RIGHT represent the up, down, left, and right arrow key values respectively.
Use the getKeyCode()
method and compare the returned value agains KeyEvent.VK_LEFT
, KeyEvent.VK_RIGHT
, KeyEvent.VK_UP
and KeyEvent.VK_DOWN
constants.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With