import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.Timer; // Unlike general-purpose Timers, Swing Timers all share the // same, pre-existing timer thread public class SwingTimers implements ActionListener { public static void main(String[] args) { new SwingTimers(); } private Timer timer1, timer2; private int counter = 1; public SwingTimers() { // Wait for five seconds, and then fire the first Swing Timer once; note that // since this Swing Timer fires only one time, the speed is irrelevant timer1 = new Timer(1, this); timer1.setInitialDelay(5000); timer1.setRepeats(false); timer1.setActionCommand("Timer1"); // Give this Swing Timer an identity timer1.start(); // Start the second Swing Timer immediately, and then fire it every two seconds timer2 = new Timer(2000, this); timer2.setInitialDelay(0); timer2.setRepeats(true); timer2.setActionCommand("Timer2"); // Give this Swing Timer an identity timer2.start(); // The line below exists solely to keep this demo program running; otherwise, // this program will end before any of the Swing Timers have a chance to fire while (timer2.isRunning()); } // This method will be called automatically whenever a Swing Timer fires public void actionPerformed(ActionEvent event) { // See if the first Swing Timer has fired if (event.getActionCommand().equals("Timer1")) System.out.println("Task #1"); // See if the second Swing Timer has fired if (event.getActionCommand().equals("Timer2")) { System.out.println("Task #2: " + counter); // Stop the second Swing Timer after it has fired five times if (counter++ == 5) timer2.stop(); } } }