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
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.
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
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.
Figure 2-1. Swing timer animation
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 ...