O'Reilly logo

Killer Game Programming in Java by Andrew Davison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Other Animation Approaches

This chapter has been concerned with developing a threaded animation loop inside a JPanel. But other ways of implementing animation in Java exist, and I'll briefly consider two of them:

  • Using the Swing timer

  • Using the utility timer from java.util.timer

Both of them use a timer to trigger method calls at regular intervals. However, I'll present timing figures that show that the Swing timer doesn't have the necessary accuracy for my needs, while the utility timer is a possible alternative.

Swing Timer Animation

The Swing timer (in javax.swing.Timer) is used as the basis of animation examples in many Java textbooks.

The essential coding technique is to set a Timer object to "tick" every few milliseconds. Each tick sends an event to a specified ActionEvent listener, triggering a call to actionPerformed(). actionPerformed() calls repaint() to send a repaint request to the JVM. Eventually, repainting reaches the paintComponent() method for the JPanel, which redraws the animation canvas. These stages are shown in Figure 2-1, which represents the test code in SwingTimerTest.java.

Swing timer animation

Figure 2-1. Swing timer animation

The SwingTimerTest class uses the Swing timer to draw the current average FPS values repeatedly into a JPanel. The period for the timer is obtained from the requested FPS given on the command line. The average FPS are calculated every second, based on FPS values ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required