Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
A Swing timer (an instance ofjavax.swing.Timer
) fires one or more action events after a specified delay. Don't confuse Swing timers with the general-purpose timer facility that was added to thejava.util
package in release 1.3. This page describes only Swing timers; you can find information on general-purpose timers in Using the Timer and TimerTask Classes in the Essential Java Classes trail.In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, pre-existing timer thread and the GUI-related task automatically executes on the event-dispatching thread. However, you might use a general-purpose timer if you don't plan on touching the GUI from the timer, or need to perform lengthy processing.
You can use Swing timers in two ways:
- To perform a task once, after a delay.
For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.- To perform a task repeatedly.
For example, you might perform animation or update a component that displays progress toward a goal.Swing timers are very easy to use. When you create the timer, you specify an action listener to be notified when the timer "goes off". The
actionPerformed
method in this listener should contain the code for whatever task you need to be performed. When you create the timer, you also specify the number of milliseconds between timer firings. If you want the timer to go off only once, you can invokesetRepeats(false)
on the timer. To start the timer, call itsstart
method. To suspend it, callstop
.Note that the Swing timer's task is performed in the event-dispatching thread. This means that the task can safely manipulate components, but it also means that the task should execute quickly. If the task might take a while to execute, then consider using a
SwingWorker
instead of or in addition to the timer. See How to Use Threads for instructions about using theSwingWorker
class and information on using Swing components in multi-threaded programs.Let's look at an example of using a timer to periodically update a component that displays progress toward a goal. Here's a picture of an application that uses a timer and a progress bar to display the progress of a long-running task.
Here's the code from
Try this:
- Run ProgressBarDemo using JavaTM Web Start. Or, to compile and run the example yourself, consult the example index for components.
- Push the Start button. A timer updates the progress bar once per second as the task executes.
ProgressBarDemo.java
that creates a timer set up to go off every second. Each time the timer goes off it receives an action event. The action listener contains the code that implements the timer's task. In this case, the handler for the action event has the job of finding out how close a thread is to completing its work and then updating the progress bar accordingly. If the thread has completed its work, the action listener also stops the timer and updates the GUI to reflect that the thread is finished.When the user presses the Start button, the program starts the timer:public final static int ONE_SECOND = 1000; ... timer = new Timer(ONE_SECOND, new ActionListener() { public void actionPerformed(ActionEvent evt) { //...Update the progress bar... if (/* thread is done */) { timer.stop(); //...Update the GUI... } } });timer.start();
The following tables list the commonly usedjavax.swing.Timer
constructors and methods. The API for using Swing timers falls into two categories:
Creating and Initializing the Timer Method or Constructor Purpose Timer(int, ActionListener)
Create a Swing timer. The int
argument specifies the number of milliseconds to pause between action events. UsesetDelay
to change the delay after construction. The second argument is an action listener, which the constructor registers with the timer. You can also register action listeners withaddActionListener
and remove them withremoveActionlistener
. Note that all timers share the same thread so there is no risk of Swing timers spawning more threads than the user's system can handle.void setDelay(int)
int getDelay()
Set or get the number of milliseconds between action events. void setInitialDelay(int)
int getInitialDelay()
Set or get the number of milliseconds to wait before firing the first action event. By default the initial delay is equal to the regular delay. void setRepeats(boolean)
boolean isRepeats()
Set or get whether the timer repeats. By default this value is true. Call setRepeats(false)
to set up a timer that fires a single action event and then stops.void setCoalesce(boolean)
boolean isCoalesce()
Set or get whether the timer coalesces multiple, pending action events into a single action event. By default this value is true. addActionListener(listener)
removeActionListener(listener)
Add or remove an action listener.
Running the Timer Method Purpose void start()
void restart()
Turn the timer on. restart
also cancels any pending action events.void stop()
Turn the timer off. boolean isRunning()
Get whether the timer is on.
This table shows the examples that usejavax.swing.Timer
and where those examples are described.
Example Where Described Notes ProgressBarDemo
This section and
How to Monitor ProgressUses a Swing timer to show periodic progress. SliderDemo
How to Use Sliders Another animation program that uses a Swing timer. Allows the user to change the timer's delay dynamically. Also shows how to use the initial delay and restart
to create a longer pause in an animation between certain frames.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.