Thread Vs javax.swing.Timer, controlling game animation in Java? Thread Vs javax.swing.Timer, controlling game animation in Java? multithreading multithreading

Thread Vs javax.swing.Timer, controlling game animation in Java?


A GUI needs to update on the EDT to make sure painting is done correctly. Read the section from the Swing tutorial on Concurrency for a complete explanation of this concept.

When you use a Swing Timer, the event is executed in the EDT so you can just tell a component to repaint itself at a new location.

When you use a Thread, then the looping is done off the EDT and you need to use SwingUtilities.invokeLater(...) to place the painting code back on the EDT.

In general, if you code is simply moving a component from one location to another then it is probably easiest to use a Timer. However, if you game involves lots of complex logic, then you don't want that logic to execute on the EDT since it will prevent the GUI from responding to events and repainting itself. In that case you might want to use a Thread.