站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

How to Use Swing Timers - Java Tutorial 5.0 英文版

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

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

How to Use Swing Timers

A Swing timer (an instance of javax.swing.Timer (in the API reference documentation)) 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 the java.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 Creating a GUI with JFC/Swing trail) in the Essential Java Classes  (in the Creating a GUI with JFC/Swing trail) 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 invoke setRepeats(false) on the timer. To start the timer, call its start method. To suspend it, call stop.

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 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. Run ProgressBarDemo using JavaTM Web Start. Or, to compile and run the example yourself, consult the example index for components.
  2. Push the Start button. A timer updates the progress bar once per second as the task executes.

Here's the code from ProgressBarDemo.java (in a .java source file) 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.
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...
        }
    }    
});
When the user presses the Start button, the program starts the timer:
timer.start();

The Timer API

The following tables list the commonly used javax.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 is used to initialize both the initial milliesecond delay, before the first event is fired, and the between-event delay, to pause between subsequent events. 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. Note that all timers ahre 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. Upon construction, this is set to be the same as the between-event delay, but then its value is independent and remains unaffected by changes to the between-event 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.

Examples that Use Timer

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

Example Where Described Notes
ProgressBarDemo This section and
How to Monitor Progress
Uses 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.


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

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.