Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Other Swing Features

How to Use Timers

The Timer(in the API reference documentation) class fires one or more ActionEvents after a specified delay. Timers are useful in the following situations:
  1. Doing something after a delay. For example, many Swing components, such as buttons, use a timer to determine when to display a tool tip.
  2. Showing periodic progress. The first example that follows, ProgressBarDemo, does this.
  3. Performing animation. See Creating an Animation Loop with Timer(in the Creating a User Interface trail) for an example and discussion.
Let's look at an example of situation #2. Here's a picture of a small demo application that uses a Timer and a progress bar to display the progress of a long-running task.

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

Once the task has begun, the timer causes the progress bar to update every second until the task completes. Here's the code from ProgressBarDemo.java that creates the timer and, when the user presses the Start button, starts it:
timer = new Timer(ONE_SECOND, new TimerListener());
. . .
timer.start();
Below is the code that implements the action listener that is notified each time the timer goes off:
class TimerListener implements ActionListener {
    public void actionPerformed(ActionEvent evt) {
        progressBar.setValue(task.getCurrent());
        if (task.done()) {
	    Toolkit.getDefaultToolkit().beep();
	    timer.stop();
	    startButton.setEnabled(true);
        }
    }
}
The bold line of code stops the timer when the task completes.


Note: The actionPerformed method defined in the Timer's action listener is invoked in the event-dispatching thread. That means that you never have to use the invokeLater method in it. For more information about using Swing components and threads in the same program, refer to Threads and Swing.

The Timer API

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

Fine Tuning the Timer's Operation
Method or Constructor Purpose
Timer(int, ActionListener) Create a timer set up with a delay and a listener. This is Timer's only constructor.
void setDelay(int)
int getDelay()
Set or get the delay between firings.
void setInitialDelay(int)
int getInitialDelay()
Set or get the delay for the initial firing. If you don't set the initial delay, then it's the same as the delay between firings.
void setRepeats(boolean)
boolean isRepeats()
Set or get whether the timer repeats. [PENDING: Default value is true?]
void setCoalesce(boolean)
boolean isCoalesce()
Set or get whether the timer coalesces multiple, pending firings into a single firing.

Running the Timer
Method Purpose
void start()
void restart()
Turn the timer on. restart cancels any pending firings.
void stop() Turn the timer off.
boolean isRunning() Get whether the timer is running.

Listening to the Timer Fire
Method Purpose
void addActionListener(ActionListener)
void removeActionListener(ActionListener)
Add or remove an action listener.

Examples that Use Timer

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

Example Where Described
ProgressBarDemo.java This section and How to Monitor Progress
AnimatorApplicationTimer.java This section.
SliderDemo.java How to Use Sliders


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Other Swing Features