In the call to keyPressed EventQueue.invokeLater(new Runnable()) , because keyPressed is called in the event flow, and repainting should be delayed.
There is an AWT event queue in which an event is processed on a single thread. When an event is processed, for example keyPressed , the GUI is frozen; other events are not processed in parallel.
Thus, such events should not do something for a long time or change the display.
The solution is to delay the code that needs to be executed.
This can be done using
EventQueue.invokeLater(new Runnable() { @Override public void run() { ... the code ... } });
In java, there is one single thread (process) that processes GUI events in an infinite loop, for example keyPressed , button click, or (indirectly) paintComponent . To do this, there is an event waiting queue called java.awt.EventQueue .
Thus, this is not done in parallel. This limitation makes encoding a little easier and better displayed on operating systems, such as the old MacOS.
Therefore, when keyPressed is called (in the event stream), the redraw call will have no effect, since it should be processed on the repaintComponent later, in the same stream.
The solution is to invokeLater , which puts the Runnable event in the event queue for future reference.
source share