Using the Swing Timer Class in an Application

Using the Swing Timer Class in an Application

The Swing Timer is a useful utility offered by the java.swing package in JDK 1.2. This code snippet shows how to use the timer in an application:

 1. ActionListener listener = new MyActionListener();2. Timer timer = new Timer(500, listener);3. timer.setInitialDelay(2000);4. timer.start();5. 6. // Other program code.

Line 1 constructs the timer. The argument “listener” is an ActionListener. Line 2 sets the initialdelay to 1000 milliseconds. If this call is not made, the initial delay will be 0. Line 3 starts the timer. Once it is started, the timer fires the first event to the ActionListener after 2000 milliseconds. Thereafter, an event is fired every 500 milliseconds. The MyActionListener implements the ActionListener interface. The actionPerformed() method prints out a message with the current system time each time the timer fires.

 1. ActionListener listener = new ActionListener () {2.   public void actionPerformed (ActionEvent event) {3.     System.out.println("Timer fired, current time = " + System.currentTimeMillis());4.   }5. }
See also  5 Tips to Manage a Remote Workforce

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist