001package horstmann.ch04_timer; 002import java.awt.FlowLayout; 003import java.awt.event.ActionListener; 004import java.util.Date; 005 006import javax.swing.JFrame; 007import javax.swing.JTextField; 008import javax.swing.Timer; 009 010/** 011 This program shows a clock that is updated once per second. 012 */ 013public class TimerTester 014{ 015 public static void main(String[] args) 016 { 017 JFrame frame = new JFrame(); 018 019 final int FIELD_WIDTH = 20; 020 final JTextField textField = new JTextField(FIELD_WIDTH); 021 022 frame.setLayout(new FlowLayout()); 023 frame.add(textField); 024 025 ActionListener listener = event -> { 026 Date now = new Date(); 027 textField.setText(now.toString()); 028 }; 029 final int DELAY = 1000; 030 // Milliseconds between timer ticks 031 Timer t = new Timer(DELAY, listener); 032 t.start(); 033 034 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 035 frame.pack(); 036 frame.setVisible(true); 037 } 038}