Fires one or more action events after a specified delay.
For example, an animation object can use a Timer
as the trigger for drawing its frames.
Setting up a timer
involves creating a Timer object,
registering one or more action listeners on it,
and starting the timer using
the start method.
For example,
the following code creates and starts a timer
that fires an action event once per second
(as specified by the first argument to the Timer constructor).
The second argument to the Timer constructor
specifies a listener to receive the timer's action events.
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
Each Timer
has one or more action listeners
and a delay
(the time between action events).
When
delay milliseconds have passed, the Timer
fires an action event to its listeners.
By default, this cycle repeats until
the stop method is called.
If you want the timer to fire only once,
invoke setRepeats(false) on the timer.
To make the delay before the first action event
different from the delay between events,
use the setInitialDelay method.
Although all Timer s perform their waiting
using a single, shared thread
(created by the first Timer object that executes),
the action event handlers for Timer s
execute on another thread -- the event-dispatching thread.
This means that the action handlers for Timer s
can safely perform operations on Swing components.
However, it also means that the handlers must execute quickly
to keep the GUI responsive.
In v 1.3, another Timer class was added
to the Java platform: java.util.Timer .
Both it and javax.swing.Timer
provide the same basic functionality,
but java.util.Timer
is more general and has more features.
The javax.swing.Timer has two features
that can make it a little easier to use with GUIs.
First, its event handling metaphor is familiar to GUI programmers
and can make dealing with the event-dispatching thread
a bit simpler.
Second, its
automatic thread sharing means that you don't have to
take special steps to avoid spawning
too many threads.
Instead, your timer uses the same thread
used to make cursors blink,
tool tips appear,
and so on.
You can find further documentation
and several examples of using timers by visiting
How to Use Timers,
a section in The Java Tutorial.
For more examples and help in choosing between
this Timer class and
java.util.Timer ,
see
Using Timers in Swing Applications,
an article in The Swing Connection.
Warning:
Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is
appropriate for short term storage or RMI between applications running
the same version of Swing. As of 1.4, support for long term storage
of all JavaBeansTM
has been added to the java.beans package.
Please see {@link java.beans.XMLEncoder}. |