Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using the JFC/Swing Packages

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 Using a Timer to Perform Animation later in this section 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.

Using a Timer to Perform Animation

Here's an example of using a Timer to implement an animation loop:
public class AnimatorApplicationTimer extends JFrame implements ActionListener {
    ...//where instance variables are declared:
    Timer timer;

    public AnimatorApplicationTimer(...) {
        ...
        // Set up a timer that calls this  
        // object's action handler.
        timer = new Timer(delay, this);
        timer.setInitialDelay(0);
        timer.setCoalesce(true);
        ...
    }

    public void startAnimation() {
        if (frozen) {
            // Do nothing.  The user has 
            // requested that we stop
            // changing the image.
        } else {
            //Start (or restart) animating!
            timer.start();
        }
    }

    public void stopAnimation() {
        //Stop the animating thread.
        timer.stop();
    }

    public void actionPerformed (ActionEvent e) {
        //Advance the animation frame.
        frameNumber++;
    
        //Display it.
        repaint();
    }
    ...
}
You can find the entire program in AnimatorApplicationTimer.java.

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.
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 page and How to Use Progress Bars
AnimatorApplicationTimer.java This page.
SliderDemo.java How to Use Sliders


Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using the JFC/Swing Packages