Reputation: 13
I am working on a pause key in my little school project, but for some reason it refuses to work. Using this code :
public void keyTyped(KeyEvent me) { //ESCAPE PLS WORK ...
code = me.getKeyCode();
System.out.println(code);
}
For some reason "code" always stays zero. I tried to put it in different voids(pressed/released etc), but it still does not work. What could be the reason?
Upvotes: 1
Views: 2968
Reputation: 718758
Here's what the javadoc says about getKeyCode()
Returns: the integer code for an actual key on the keyboard. (For
KEY_TYPED
events, the keyCode isVK_UNDEFINED
.)
And the value of VK_UNDEFINED
is zero.
The javadoc also says:
public static final int KEY_TYPED
The "key typed" event. This event is generated when a character is entered. In the simplest case, it is produced by a single key press. Often, however, characters are produced by series of key presses, and the mapping from key pressed events to key typed events may be many-to-one or many-to-many.
So maybe you are looking at the wrong kind of key events. Maybe should be looking at the KEY_PRESSED
or KEY_RELEASED
events rather than the KEY_TYPED
events.
Upvotes: 4
Reputation: 2266
Why not try the keyPressed()
method again as in the example below:
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch( code ) {
case KeyEvent.VK_UP:
// handle up
System.out.println(code);
break;
case KeyEvent.VK_DOWN:
// handle down
break;
case KeyEvent.VK_LEFT:
// handle left
break;
case KeyEvent.VK_RIGHT :
// handle right
break;
}
}
Note that you must expect an integer.
Upvotes: 2