Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have this very straight forward question regarding Thread and Timer classes in Java as a way of creating game animations. Which is better of the two? What are really the differences between the two and which is the most preferred in terms of animation in Java? I hope my question makes since, this is in someway related to the answers i got from one of my question here ... question

like image 335
ultrajohn Avatar asked Mar 03 '10 16:03

ultrajohn


1 Answers

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.

like image 140
camickr Avatar answered Nov 18 '22 09:11

camickr