I'm making a turn based game where the user moves a player with the arrow keys. I use wait() to stop the game from continuing until the player inputs an arrow. My wait looks like this:
try {
synchronized(sharedObject) {
sharedObject.wait();
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
And my key input (in another class) looks like this:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized(lockObject) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_UP) {
playerInput = "UP";
System.out.println(playerInput);
lockObject.notify();
}else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
playerInput = "DOWN";
System.out.println(playerInput);
lockObject.notify();
}else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
playerInput = "LEFT";
System.out.println(playerInput);
lockObject.notify();
}else if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {
playerInput = "RIGHT";
System.out.println(playerInput);
lockObject.notify();
}
break;
}
}
return true;
}
});
When sharedObject.wait(); is called, the JFrame turns blank and the whole application freezes (I have to force close it everytime.) I've tested the code before wait() is called and it works up until that point. I playerInput is a string that I have to see if the user inputs are being processed.
Any help would be greatly appreciated.
This is because calling
wait()blocks all execution, including the built-in event handling mechanisms that you get from using Swing. You should learn about event handling in order to do what you want correctly.In short, don't block the main thread. Only use
wait()if you are spawing your own threads and actually need this behavior.