Swing Timer

Swing Timer is a part of the Java Swing library. It offers a simple way to perform tasks repeatedly with a defined delay between each execution. This functionality is especially useful for scenarios when updating live data, creating animations, or scheduling periodic checks.

Following is a hands-on example demonstrating how to utilize Swing Timers:

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SwingTimerDemo extends JFrame {
	private JLabel timerLabel;
	private Timer swingTimer;
	private int secondsPassed;

	public SwingTimerDemo() {
		setTitle("Swing Timer Demo");
		setSize(300, 150);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);

		timerLabel = new JLabel("Seconds passed: 0");
		timerLabel.setFont(new Font("Arial", Font.BOLD, 20));
		timerLabel.setHorizontalAlignment(SwingConstants.CENTER);

		swingTimer = new Timer(1000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				secondsPassed++;
				timerLabel.setText("Seconds passed: " + secondsPassed);
			}
		});
		swingTimer.start();

		add(timerLabel);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new SwingTimerDemo().setVisible(true);
			}
		});
	}

}

Output:

swing timer
Swing Timer 2