FileDocCategorySizeDatePackage
Timer.javaAPI DocJava SE 5 API16569Fri Aug 26 14:57:58 BST 2005javax.swing

Timer

public class Timer extends Object implements Serializable
Fires one or more action events after a specified delay. For example, an animation object can use a Timer as the trigger for drawing its frames.

Setting up a timer involves creating a Timer object, registering one or more action listeners on it, and starting the timer using the start method. For example, the following code creates and starts a timer that fires an action event once per second (as specified by the first argument to the Timer constructor). The second argument to the Timer constructor specifies a listener to receive the timer's action events.

int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();

Each Timer has one or more action listeners and a delay (the time between action events). When delay milliseconds have passed, the Timer fires an action event to its listeners. By default, this cycle repeats until the stop method is called. If you want the timer to fire only once, invoke setRepeats(false) on the timer. To make the delay before the first action event different from the delay between events, use the setInitialDelay method.

Although all Timers perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timers execute on another thread -- the event-dispatching thread. This means that the action handlers for Timers can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

In v 1.3, another Timer class was added to the Java platform: java.util.Timer. Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don't have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

You can find further documentation and several examples of using timers by visiting How to Use Timers, a section in The Java Tutorial. For more examples and help in choosing between this Timer class and java.util.Timer, see Using Timers in Swing Applications, an article in The Swing Connection.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see {@link java.beans.XMLEncoder}.

see
java.util.Timer java.util.Timer
version
1.45 05/05/04
author
Dave Moore

Fields Summary
protected EventListenerList
listenerList
private boolean
notify
int
initialDelay
int
delay
boolean
repeats
boolean
coalesce
Runnable
doPostEvent
private static boolean
logTimers
long
expirationTime
Timer
nextTimer
boolean
running
Constructors Summary
public Timer(int delay, ActionListener listener)
Creates a Timer that will notify its listeners every delay milliseconds. If delay is less than or equal to zero the timer will fire as soon as it is started. If listener is not null, it's registered as an action listener on the timer.

param
delay the number of milliseconds between action events
param
listener an initial listener; can be null
see
#addActionListener
see
#setInitialDelay
see
#setRepeats



                                                                             
         
        super();
        this.delay = delay;
        this.initialDelay = delay;

        doPostEvent = new DoPostEvent();

	if (listener != null) {
	    addActionListener(listener);
	}
    
Methods Summary
public voidaddActionListener(java.awt.event.ActionListener listener)
Adds an action listener to the Timer.

param
listener the listener to add
see
#Timer

        listenerList.add(ActionListener.class, listener);
    
synchronized voidcancelEvent()
Resets the internal state to indicate this Timer shouldn't notify any of its listeners. This does not stop a repeatable Timer from firing again, use stop for that.

        notify = false;
    
protected voidfireActionPerformed(java.awt.event.ActionEvent e)
Notifies all listeners that have registered interest for notification on this event type.

param
e the action event to fire
see
EventListenerList

        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();

        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i=listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==ActionListener.class) {
                ((ActionListener)listeners[i+1]).actionPerformed(e);
            }          
        }
    
public java.awt.event.ActionListener[]getActionListeners()
Returns an array of all the action listeners registered on this timer.

return
all of the timer's ActionListeners or an empty array if no action listeners are currently registered
see
#addActionListener
see
#removeActionListener
since
1.4

        return (ActionListener[])listenerList.getListeners(
                ActionListener.class);
    
public intgetDelay()
Returns the delay, in milliseconds, between firings of action events.

see
#setDelay
see
#getInitialDelay

        return delay;
    
public intgetInitialDelay()
Returns the Timer's initial delay.

see
#setInitialDelay
see
#setDelay

        return initialDelay;
    
public T[]getListeners(java.lang.Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Timer. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a Timer instance t for its action listeners with the following code:

ActionListener[] als = (ActionListener[])(t.getListeners(ActionListener.class));
If no such listeners exist, this method returns an empty array.

param
listenerType the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
return
an array of all objects registered as FooListeners on this timer, or an empty array if no such listeners have been added
exception
ClassCastException if listenerType doesn't specify a class or interface that implements java.util.EventListener
see
#getActionListeners
see
#addActionListener
see
#removeActionListener
since
1.3

 
	return listenerList.getListeners(listenerType); 
    
public static booleangetLogTimers()
Returns true if logging is enabled.

return
true if logging is enabled; otherwise, false
see
#setLogTimers

        return logTimers;
    
public booleanisCoalesce()
Returns true if the Timer coalesces multiple pending action events.

see
#setCoalesce

        return coalesce;
    
public booleanisRepeats()
Returns true (the default) if the Timer will send an action event to its listeners multiple times.

see
#setRepeats

        return repeats;
    
public booleanisRunning()
Returns true if the Timer is running.

see
#start

        return timerQueue().containsTimer(this);
    
synchronized voidpost()

        if (notify == false || !coalesce) {
            notify = true;
            SwingUtilities.invokeLater(doPostEvent);
        }
    
public voidremoveActionListener(java.awt.event.ActionListener listener)
Removes the specified action listener from the Timer.

param
listener the listener to remove

        listenerList.remove(ActionListener.class, listener);
    
public voidrestart()
Restarts the Timer, canceling any pending firings and causing it to fire with its initial delay.

        stop();
        start();
    
public voidsetCoalesce(boolean flag)
Sets whether the Timer coalesces multiple pending ActionEvent firings. A busy application may not be able to keep up with a Timer's event generation, causing multiple action events to be queued. When processed, the application sends these events one after the other, causing the Timer's listeners to receive a sequence of events with no delay between them. Coalescing avoids this situation by reducing multiple pending events to a single event. Timers coalesce events by default.

param
flag specify false to turn off coalescing

        boolean old = coalesce;
        coalesce = flag;
        if (!old && coalesce) {
            // We must do this as otherwise if the Timer once notified
            // in !coalese mode notify will be stuck to true and never
            // become false.
            cancelEvent();
        }
    
public voidsetDelay(int delay)
Sets the Timer's delay, the number of milliseconds between successive action events.

param
delay the delay in milliseconds
see
#setInitialDelay

        if (delay < 0) {
            throw new IllegalArgumentException("Invalid delay: " + delay);
        }
        else {
            this.delay = delay;
        }
    
public voidsetInitialDelay(int initialDelay)
Sets the Timer's initial delay, which by default is the same as the between-event delay. This is used only for the first action event. Subsequent action events are spaced using the delay property.

param
initialDelay the delay, in milliseconds, between the invocation of the start method and the first action event fired by this timer
see
#setDelay

        if (initialDelay < 0) {
            throw new IllegalArgumentException("Invalid initial delay: " +
                                               initialDelay);
        }
        else {
            this.initialDelay = initialDelay;
        }
    
public static voidsetLogTimers(boolean flag)
Enables or disables the timer log. When enabled, a message is posted to System.out whenever the timer goes off.

param
flag true to enable logging
see
#getLogTimers

        logTimers = flag;
    
public voidsetRepeats(boolean flag)
If flag is false, instructs the Timer to send only one action event to its listeners.

param
flag specify false to make the timer stop after sending its first action event

        repeats = flag;
    
public voidstart()
Starts the Timer, causing it to start sending action events to its listeners.

see
#stop

        timerQueue().addTimer(this,
                              System.currentTimeMillis() + getInitialDelay());
    
public voidstop()
Stops the Timer, causing it to stop sending action events to its listeners.

see
#start

        timerQueue().removeTimer(this);
        cancelEvent();
    
javax.swing.TimerQueuetimerQueue()
Returns the timer queue.

        return TimerQueue.sharedInstance();