Java Data Type How to - Clock that refreshes on Dialog








Question

We would like to know how to clock that refreshes on Dialog.

Answer

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
//from  w  w w. j a v  a  2  s  . c o  m
public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                final Date date = new Date();
                final JLabel timeLabel = new JLabel(date.toString());
                Timer timer = new Timer(1000, new ActionListener(){
                    public void actionPerformed(ActionEvent e) {
                        date.setTime(System.currentTimeMillis());
                        timeLabel.setText(date.toString());
                    }
                });
                timer.start();
                JOptionPane.showMessageDialog(null, timeLabel);
            }
        });
    }
}