APIdia Launch Partner
Top Description Inners Fields Constructors Methods
javax.swing

public Class Timer

extends Object
implements Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable
Known Direct Subclasses
javax.swing.JTree.TreeTimer
Annotations
@SuppressWarnings:serial
Imports
java.awt.event.ActionEvent, .ActionListener, java.io.IOException, .InvalidObjectException, .ObjectInputStream, .Serial, .Serializable, java.util.EventListener, java.util.concurrent.atomic.AtomicBoolean, java.util.concurrent.locks.Lock, .ReentrantLock, javax.swing.event.EventListenerList

Fires one or more ActionEvents at specified intervals. An example use is an animation object that uses 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();

Timers are constructed by specifying both a delay parameter and an ActionListener. The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds. Once the timer has been started, it waits for the initial delay before firing its first ActionEvent to registered listeners. After this first event, it continues to fire events every time the between-event delay has elapsed, until it is stopped.

After construction, the initial delay and the between-event delay can be changed independently, and additional ActionListeners may be added.

If you want the timer to fire only the first time and then stop, invoke setRepeats(false) on the timer.

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.

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 JavaBeans has been added to the java.beans package. Please see java.beans.XMLEncoder.

Author
Dave Moore
Since
1.2
See Also
java.util.Timer

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv class
Timer.DoPostEvent

DoPostEvent is a runnable class that fires actionEvents to the listeners on the EventDispatchThread, via invokeLater.

Field Summary

Modifier and TypeField and Description
private volatile String
private volatile boolean
private volatile int
pack-priv transient TimerQueue.DelayedTimer
private final transient Runnable
private volatile int
protected EventListenerList
listenerList

The collection of registered listeners

private final transient Lock
private static volatile boolean
private final transient AtomicBoolean
private volatile boolean

Constructor Summary

AccessConstructor and Description
public
Timer(int
milliseconds for the initial and between-event delay
delay
,
ActionListener
an initial listener; can be null
listener
)

Creates a Timer and initializes both the initial delay and between-event delay to delay milliseconds.

Method Summary

Modifier and TypeMethod and Description
public void
addActionListener(ActionListener
the listener to add
listener
)

Adds an action listener to the Timer.

pack-priv void
cancelEvent()

Resets the internal state to indicate this Timer shouldn't notify any of its listeners.

private static void
checkDelay(int delay, String message)

protected void
fireActionPerformed(ActionEvent
the action event to fire
e
)

Notifies all listeners that have registered interest for notification on this event type.

public String

Returns:

the action command used in firing events
getActionCommand
()

Returns the string that will be delivered as the action command in ActionEvents fired by this timer.

public ActionListener[]

Returns:

all of the timer's ActionListeners or an empty array if no action listeners are currently registered
getActionListeners
()

Returns an array of all the action listeners registered on this timer.

public int

Returns:

the delay, in milliseconds, between firings of action events
getDelay
()

Returns the delay, in milliseconds, between firings of action events.

public int

Returns:

the Timer's initial delay, in milliseconds
getInitialDelay
()

Returns the Timer's initial delay.

public <
the type of EventListener class being requested
T extends EventListener
>
T[]

Returns:

an array of all objects registered as FooListeners on this timer, or an empty array if no such listeners have been added
getListeners
(Class<T>
the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
listenerType
)

Returns an array of all the objects currently registered as FooListeners upon this Timer.

pack-priv Lock
public static boolean

Returns:

true if logging is enabled; otherwise, false
getLogTimers
()

Returns true if logging is enabled.

public boolean

Returns:

true if the Timer coalesces multiple pending action events
isCoalesce
()

Returns true if the Timer coalesces multiple pending action events.

public boolean

Returns:

true if the Timer will send an action event to its listeners multiple times
isRepeats
()

Returns true (the default) if the Timer will send an action event to its listeners multiple times.

public boolean

Returns:

true if the Timer is running, false otherwise
isRunning
()

Returns true if the Timer is running.

pack-priv void
post()

private void
private Object
public void
removeActionListener(ActionListener
the listener to remove
listener
)

Removes the specified action listener from the Timer.

public void
restart()

Restarts the Timer, canceling any pending firings and causing it to fire with its initial delay.

public void
setActionCommand(String
the action command
command
)

Sets the string that will be delivered as the action command in ActionEvents fired by this timer.

public void
setCoalesce(boolean
specify false to turn off coalescing
flag
)

Sets whether the Timer coalesces multiple pending ActionEvent firings.

public void
setDelay(int
the delay in milliseconds
delay
)

Sets the Timer's between-event delay, the number of milliseconds between successive action events.

public void
setInitialDelay(int
the initial delay, in milliseconds
initialDelay
)

Sets the Timer's initial delay, the time in milliseconds to wait after the timer is started before firing the first event.

public static void
setLogTimers(boolean
true to enable logging
flag
)

Enables or disables the timer log.

public void
setRepeats(boolean
specify false to make the timer stop after sending its first action event
flag
)

If flag is false, instructs the Timer to send only one action event to its listeners.

public void
start()

Starts the Timer, causing it to start sending action events to its listeners.

public void
stop()

Stops the Timer, causing it to stop sending action events to its listeners.

private TimerQueue
timerQueue()

Returns the timer queue.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

actionCommandback to summary
private volatile String actionCommand
coalesceback to summary
private volatile boolean coalesce
delayback to summary
private volatile int delay
delayedTimerback to summary
pack-priv transient TimerQueue.DelayedTimer delayedTimer
doPostEventback to summary
private final transient Runnable doPostEvent
initialDelayback to summary
private volatile int initialDelay
listenerListback to summary
protected EventListenerList listenerList

The collection of registered listeners

lockback to summary
private final transient Lock lock
logTimersback to summary
private static volatile boolean logTimers
notifyback to summary
private final transient AtomicBoolean notify
repeatsback to summary
private volatile boolean repeats

Constructor Detail

Timerback to summary
public Timer(int delay, ActionListener listener)

Creates a Timer and initializes both the initial delay and between-event delay to delay milliseconds. If delay is less than or equal to zero, the timer fires as soon as it is started. If listener is not null, it's registered as an action listener on the timer.

Parameters
delay:int

milliseconds for the initial and between-event delay

listener:ActionListener

an initial listener; can be null

See Also
addActionListener, setInitialDelay, setRepeats

Method Detail

addActionListenerback to summary
public void addActionListener(ActionListener listener)

Adds an action listener to the Timer.

Parameters
listener:ActionListener

the listener to add

See Also
Timer
cancelEventback to summary
pack-priv void cancelEvent()

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.

checkDelayback to summary
private static void checkDelay(int delay, String message)
fireActionPerformedback to summary
protected void fireActionPerformed(ActionEvent e)

Notifies all listeners that have registered interest for notification on this event type.

Parameters
e:ActionEvent

the action event to fire

See Also
EventListenerList
getActionCommandback to summary
public String getActionCommand()

Returns the string that will be delivered as the action command in ActionEvents fired by this timer. May be null, which is also the default.

Returns:String

the action command used in firing events

Since
1.6
getActionListenersback to summary
public ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this timer.

Returns:ActionListener[]

all of the timer's ActionListeners or an empty array if no action listeners are currently registered

Since
1.4
See Also
addActionListener, removeActionListener
getDelayback to summary
public int getDelay()

Returns the delay, in milliseconds, between firings of action events.

Returns:int

the delay, in milliseconds, between firings of action events

See Also
setDelay, getInitialDelay
getInitialDelayback to summary
public int getInitialDelay()

Returns the Timer's initial delay.

Returns:int

the Timer's initial delay, in milliseconds

See Also
setInitialDelay, setDelay
getListenersback to summary
public <T extends EventListener> T[] getListeners(Class<T> 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.
Parameters
<T>
the type of EventListener class being requested
listenerType:Class<T>

the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener

Returns:T[]

an array of all objects registered as FooListeners on this timer, or an empty array if no such listeners have been added

Exceptions
ClassCastException:
if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since
1.3
See Also
getActionListeners, addActionListener, removeActionListener
getLockback to summary
pack-priv Lock getLock()
getLogTimersback to summary
public static boolean getLogTimers()

Returns true if logging is enabled.

Returns:boolean

true if logging is enabled; otherwise, false

See Also
setLogTimers
isCoalesceback to summary
public boolean isCoalesce()

Returns true if the Timer coalesces multiple pending action events.

Returns:boolean

true if the Timer coalesces multiple pending action events

See Also
setCoalesce
isRepeatsback to summary
public boolean isRepeats()

Returns true (the default) if the Timer will send an action event to its listeners multiple times.

Returns:boolean

true if the Timer will send an action event to its listeners multiple times

See Also
setRepeats
isRunningback to summary
public boolean isRunning()

Returns true if the Timer is running.

Returns:boolean

true if the Timer is running, false otherwise

See Also
start
postback to summary
pack-priv void post()
readObjectback to summary
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
Annotations
@Serial
readResolveback to summary
private Object readResolve()
Annotations
@Serial
removeActionListenerback to summary
public void removeActionListener(ActionListener listener)

Removes the specified action listener from the Timer.

Parameters
listener:ActionListener

the listener to remove

restartback to summary
public void restart()

Restarts the Timer, canceling any pending firings and causing it to fire with its initial delay.

setActionCommandback to summary
public void setActionCommand(String command)

Sets the string that will be delivered as the action command in ActionEvents fired by this timer. null is an acceptable value.

Parameters
command:String

the action command

Since
1.6
setCoalesceback to summary
public void setCoalesce(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.

Parameters
flag:boolean

specify false to turn off coalescing

setDelayback to summary
public void setDelay(int delay)

Sets the Timer's between-event delay, the number of milliseconds between successive action events. This does not affect the initial delay property, which can be set by the setInitialDelay method.

Parameters
delay:int

the delay in milliseconds

See Also
setInitialDelay
setInitialDelayback to summary
public void setInitialDelay(int initialDelay)

Sets the Timer's initial delay, the time in milliseconds to wait after the timer is started before firing the first 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.

Parameters
initialDelay:int

the initial delay, in milliseconds

See Also
setDelay
setLogTimersback to summary
public static void setLogTimers(boolean flag)

Enables or disables the timer log. When enabled, a message is posted to System.out whenever the timer goes off.

Parameters
flag:boolean

true to enable logging

See Also
getLogTimers
setRepeatsback to summary
public void setRepeats(boolean flag)

If flag is false, instructs the Timer to send only one action event to its listeners.

Parameters
flag:boolean

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

startback to summary
public void start()

Starts the Timer, causing it to start sending action events to its listeners.

See Also
stop
stopback to summary
public void stop()

Stops the Timer, causing it to stop sending action events to its listeners.

See Also
start
timerQueueback to summary
private TimerQueue timerQueue()

Returns the timer queue.

javax.swing back to summary

pack-priv Class Timer.DoPostEvent

extends Object
implements Runnable
Class Inheritance
All Implemented Interfaces
java.lang.Runnable

DoPostEvent is a runnable class that fires actionEvents to the listeners on the EventDispatchThread, via invokeLater.
See Also
Timer#post

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
pack-priv Timer
public void
run()

Implements java.lang.Runnable.run.

Runs this operation.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

DoPostEventback to summary
pack-priv DoPostEvent()

Method Detail

getTimerback to summary
pack-priv Timer getTimer()
runback to summary
public void run()

Implements java.lang.Runnable.run.

Doc from java.lang.Runnable.run.

Runs this operation.