The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Creating a GUI with JFC/Swing
Lesson: Using Other Swing Features

How to Use Timers

The Timer(in the API reference documentation) class fires one or more action events after a specified delay. You can use a timer in either of two ways: Note that the 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 the SwingWorker 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.

An application that uses a timer to periodically update a progress bar


Try this: 
  1. Compile and run the application. The main source file is ProgressBarDemo.java. You will also need two other source files.
    See Getting Started with Swing if you need help compiling or running this application.
  2. Push the Start button. Watch the progress bar as the task makes progress.

Here's the code from ProgressBarDemo.java that creates a timer set up to "go off" every second. Each time a timer goes off it fires an action event. Conveniently, the constructor also takes an action listener, which is implemented as an anonymous inner class. The action listener contains the code that implements the timer's task.
public final static int ONE_SECOND = 1000;
...
timer = new Timer(ONE_SECOND, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
	//...Perform a task...
    }    
});
When the user presses the Start button, the program starts the timer:
timer.start();
When the task is finished, the timer's action listener stops the timer:
if (/* task is done */) {
    ...
    timer.stop();
    ...
}

The Timer API

The following tables list the commonly used Timer constructors and methods. The API for using timers falls into two categories:

Creating and Initializing the Timer
Method or Constructor Purpose
Timer(int, ActionListener) Create a timer. The int argument specifies the number of milliseconds to pause between action events. Use setDelay 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 with addActionListener and remove them with removeActionlistener.
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.

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

Examples that Use Timer

This table shows the examples that use Timer and where those examples are described.

Example Where Described Notes
ProgressBarDemo This section and
How to Monitor Progress
Uses a timer to show periodic progress.
AnimatorApplicationTimer and
AnimatorAppletTimer
Creating an Animation Loop with Timer Uses a timer to control an animation loop.
SliderDemo How to Use Sliders Another animation program that uses a 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.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search