This question already has an answer here:
I am a beginner in Java an I have been looking on how to detect if the user pressed a key (such a the arrow keys). Apparently there are a lot of ways to do such a thing, and I found that this method should work for me:
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;
}
}
The problem is that I have no idea what a KeyEvent is.
Can anyone tell me what to put in the parentheses when I call the method and show me an example please?
PS: don't send me to an other site, I probably have already looked at it and they just confuse me more...
An event which indicates that a keystroke occurred in a component.
This event is generated by a component object (such as a text field) when a key is
pressed, released, or typed. The event is passed to every KeyListener or KeyAdapter object
which registered to receive such events using the component's addKeyListener method.
(KeyAdapter objects implement the KeyListener interface.) Each such listener object gets this KeyEvent when the event occurs.
and using that event object, you can get the event details like what key has been pressed using
e.getKeyCode()
some more methods like that.