Java Reference
In-Depth Information
9.8 The Timer Class
A timer object, created from the Timer class of the javax.
swing package, can be thought of as a GUI component.
However, unlike other components, it does not have a visual
representation that appears on the screen. Instead, as the
name implies, it helps us manage an activity over time.
A timer object generates an action event at regular inter-
vals. To perform an animation, we set up a timer to generate an action event peri-
odically, then update the animation graphics in the action listener. The methods
of the Timer class are shown in Figure 9.8.
The program shown in Listing 9.15 displays the image of a smiling face that
seems to glide across the program window at an angle, bouncing off of the win-
dow edges.
The constructor of the ReboundPanel class, shown in Listing 9.16, creates a
Timer object. The first parameter to the Timer constructor is the delay in milli-
seconds. The second parameter to the constructor is the listener that handles the
action events of the timer. The constructor also sets up the initial position for the
image and the number of pixels it will move, in both the vertical and horizontal
directions, each time the image is redrawn.
KEY CONCEPT
A Timer object generates action
events at regular intervals and can
be used to control an animation.
VideoNote
Example using the
Timer class.
Timer ( int delay, ActionListener listener)
Constructor: Creates a timer that generates an action event at
regular intervals, specified by the delay. The event will be handled
by the specified listener.
void addActionListener (ActionListener listener)
Adds an action listener to the timer.
boolean isRunning ()
Returns true if the timer is running.
void setDelay ( int delay)
Sets the delay of the timer.
void start ()
Starts the timer, causing it to generate action events.
void stop ()
Stops the timer, causing it to stop generating action events.
FIGURE 9.8 Some methods of the Timer class
 
Search WWH ::




Custom Search