Imagine you have two threads:
- AWT Thread (which deals with mouse and key events) and
- Main Thread.
And imagine that this is what happens when you run your program:
Main Thread: new Example().mainLoop();
Main Thread: mainLoop();
Main Thread: while( !keys[KevEvent.VK_ESCAPE] ) { … }; // keys[KevEvent.VK_ESCAPE] is false, so continue looping.
Main Thread: while( !keys[KevEvent.VK_ESCAPE] ) { … }; // keys[KevEvent.VK_ESCAPE] is false, so continue looping.
Main Thread: while( !keys[KevEvent.VK_ESCAPE] ) { … }; // keys[KevEvent.VK_ESCAPE] is false, so continue looping.
Now imagine that the escape key is pressed:
AWT Thread: processKeyEvent(KeyEvent e) -> e.getID() is KeyEvent.KEY_PRESSED -> keys[KevEvent.VK_ESCAPE] is now true.
AWT Thread: processKeyEvent(KeyEvent e) -> e.getID() is KeyEvent.KEY_RELEASED -> keys[KevEvent.VK_ESCAPE] is now false.
Main Thread: while( !keys[KevEvent.VK_ESCAPE] ) { … }; // keys[KevEvent.VK_ESCAPE] is false, so continue looping.
Main Thread: while( !keys[KevEvent.VK_ESCAPE] ) { … }; // keys[KevEvent.VK_ESCAPE] is false, so continue looping.
Main Thread: while( !keys[KevEvent.VK_ESCAPE] ) { … }; // keys[KevEvent.VK_ESCAPE] is false, so continue looping.
Basically I am saying the code you have might have unpredictable results due to threading issues.
After a KEY_PRESSED event, IF mainLoop() is not called before the subsequent KEY_RELEASED event then mainLoop() will never see keys[KevEvent.VK_ESCAPE] as true.