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 ...

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.