-1

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...

Dalex
  • 359
  • 2
  • 3
  • 12
  • Check this out http://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key – SamoanProgrammer May 24 '14 at 03:51
  • [The Java Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html) explains this in significant detail. Was there something there which you did not understand? – Matt Ball May 24 '14 at 03:51
  • KeyListener will only I work if when it is registered to a component which is displayed on the screen and the component is focusable and has key board focus – MadProgrammer May 24 '14 at 04:09

1 Answers1

1
public class KeyEvent
extends InputEvent

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.

Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27