jeudi 5 février 2015

KeyListener ignores if-statements

In this code:



public class KeyManager implements KeyListener{

public void keyPressed(KeyEvent e) {
boolean spacePressed = false;


if(e.getKeyCode() == KeyEvent.VK_SPACE){
if(spacePressed == false){
spacePressed = true;
System.out.println("Hello world");
}
}
}


I am trying to have space only print out "Hello world" once, then switch spacePressed to true and not do anything more from that point onward.


Using System prints I've managed to find out that it does change spacePressed to true after I've pressed it, but for some reason I can press space again and once more print out "Hello world".


In short, the compiler seems to ignore the if statement and just continue reading, which isn't supposed to happen.


Aucun commentaire:

Enregistrer un commentaire