How do I use Swing Timer class?

In this example you’ll see how to use java.swing.Timer class to create a text clock program.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class TimerDemo extends JFrame {
    public static final DateFormat df = new SimpleDateFormat("hh:mm:ss");

    public TimerDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 200);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));

        final JLabel label = new JLabel();
        container.add(label);

        Timer timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Calendar now = Calendar.getInstance();

                String timeText = "" + df.format(now.getTime()) + "";

                label.setText(timeText);
            }
        });
        timer.start();
    }

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

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply