Java Data Type How to - Create UI with Date that refreshes








Question

We would like to know how to create UI with Date that refreshes.

Answer

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
//from   w  w w.  j a va 2 s .  c  o  m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Main extends JFrame {
  public static Timer t;
  public JLabel jlabel4 = new JLabel();
  public Main() {
    this.setLayout(null);
    jlabel4.setBounds(0, 0, 100, 30);
    this.add(jlabel4);
    this.pack();
    t = new Timer(1000, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        jlabel4.setText(new SimpleDateFormat("HH:mm:ss", Locale.FRANCE)
            .format(new Date()));
      }
    });
    t.start();
    setSize(new Dimension(200, 60));
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}