The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)

 < Day Day Up > 

A Swing timer (an instance of javax.swing.Timer [81] ) fires one or more action events after a specified delay. Don't confuse it with the general-purpose timer facility that was added to the java.util package in release 1.3. [82]

[81] javax.swing.Timer API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Timer.html.

[82] This section describes only Swing timers; you can find information on general-purpose timers in "Using the Timer and TimerTask Classes" in The Java Tutorial , available on the CD and online: http://java.sun.com/docs/books/tutorial/essential/threads/timer.html.

In general, we recommend using Swing timers rather than general-purpose timers for GUI-related tasks because Swing timers all share the same, preexisting 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 you 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 carried out. 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 it. To start the timer, call its start method. To suspend it, call stop .

The Swing timer's task is performed in the event-dispatching thread. This means that it can safely manipulate components , but it also means that the task should execute quickly. If it might take a while to execute, consider using a SwingWorker instead of or in addition to the timer. See How to Use Threads (page 632) for instructions on using the SwingWorker class and information on using Swing components in multi-threaded programs.

Figure 40 is an example of using a timer to periodically update a component that displays progress toward a goal.

Figure 40. A screenshot of an application that uses a timer and a progress bar to display the progress of a long-running task.

Try This:

  1. Run ProgressBarDemo using Java Web Start or compile and run the example yourself. [83]

    [83] To run ProgressBarDemo using Java Web Start, click the ProgressBarDemo link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#ProgressBarDemo .

  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 that creates a timer set 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 to find out how close a thread is to completing its work and then update the progress bar accordingly . If the thread has completed its work, the action listener also stops the timer and updates the GUI to show 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

Tables 23 and 24 list the commonly used javax.swing.Timer constructors and methods . You can also refer to the API documentation for javax.swing.Timer at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Timer.html.

Table 23. 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. 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 . 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.

Table 24. 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 Timers

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

Example

Where Described

Notes

ProgressBarDemo

This section and How to Use Progress Bars (page 300)

Uses a Swing timer to show periodic progress.

SliderDemo

How to Use Sliders (page 348)

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 .

 < Day Day Up > 

Категории