01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package horstmann.ch04_timer;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.Timer;

/**
   This program shows a clock that is updated once per second.
 */
public class TimerTester
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();

    final int FIELD_WIDTH = 20;
    final JTextField textField = new JTextField(FIELD_WIDTH);

    frame.setLayout(new FlowLayout());
    frame.add(textField);

    ActionListener listener = event -> {
      Date now = new Date();
      textField.setText(now.toString());
    };
    final int DELAY = 1000;
    // Milliseconds between timer ticks
    Timer t = new Timer(DELAY, listener);
    t.start();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}