Java Reference
In-Depth Information
Using Timer Objects
After a Timer object has been created, you need to start() it. Once the Timer is started, the
ActionListener will be notified after the given number of milliseconds. If the system is busy,
the delay could be longer, but it won't be shorter.
If there comes a time when you want to stop a Timer , call its stop() method. The Timer also
has a restart() method, which calls stop() and start() , restarting the delay period.
To demonstrate, Listing 2-7 defines an ActionListener that simply prints a message. You
then create a Timer to call this listener every half second. After creating the timer, you need to
start it.
Listing 2-7. Swing Timer Sample
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TimerSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Hello World Timer");
}
};
Timer timer = new Timer(500, actionListener);
timer.start();
}
};
EventQueue.invokeLater(runner);
}
}
Note A Timer doesn't start up the AWT event-dispatch thread on its own.
Timer Properties
Table 2-1 lists the six properties of Timer . Four allow you to customize the behavior of the timer.
running tells you if a timer has been started but not stopped, and actionListeners gets you the
list of action listeners.
 
Search WWH ::




Custom Search