Sasha Prostotin Sasha Prostotin - 12 days ago 8
Java Question

me.getKeyCode() always returns zero

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?

Answer

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.