The Timer Class

The Timer class provides a mechanism to generate timed events. It has properties and events, and thus can be used in application builders that understand JavaBeans. It fires an ActionEvent at a given time. The timer can be set to repeat, and an optional initial delay can be set before the repeating event starts.

import javax.swing.*;
import javax.swing.Timer;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

class ClockLabel extends JLabel implements ActionListener {

	public ClockLabel() {
		super("" + new Date());
		Timer t = new Timer(1000, this);
		t.start();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		setText((new Date()).toString());

	}
}

public class ClockTest extends JFrame {

	public ClockTest() {
		super("Timer Demo");
		setSize(300, 100);
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		ClockLabel clock = new ClockLabel();
		getContentPane().add(clock, BorderLayout.NORTH);
	}

	public static void main(String args[]) {
		ClockTest ct = new ClockTest();
		ct.setVisible(true);
	}
}