1
2
3
4
5
6
7
8
9
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
// TextClock2.java -- Uses Timer, Calendar, JTextField.
// -- Fred Swartz, 1999-05-01, 2001-11-02
// 2002-11-07 Separate component
// Enhancements: center, leading zeros, uneditable, 12 hour,
// alarm, timer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Calendar; // only need this one class
///////////////////////////////////////////////////////////// TextClock2
public class TextClock2 {
//============================================================= main
public static void main(String[] args) {
JFrame clock = new TextClockWindow();
clock.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clock.setVisible(true);
}//end main
}//endclass TextClock2
//////////////////////////////////////////////////////// TextClockWindow
class TextClockWindow extends JFrame {
//=========================================== instance variables
private Clock myClock; // set by timer listener
//================================================== constructor
public TextClockWindow() {
// Build the GUI - only one panel
myClock = new Clock();
Container content = this.getContentPane();
content.setLayout(new FlowLayout());
content.add(myClock);
this.setTitle("A Clock");
this.pack();
}//end constructor
}//endclass TextClock
////////////////////////////////////////////////////////////////// Clock
class Clock extends JTextField {
javax.swing.Timer t; // timer used to update clock.
//================================================== constructor
public Clock() {
this.setColumns(6); // set approximate width of field
this.setFont(new Font("sansserif", Font.PLAIN, 48));
//--- Create a 1-second timer and action listener for it.
t = new javax.swing.Timer(1000,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
int h = now.get(Calendar.HOUR_OF_DAY);
int m = now.get(Calendar.MINUTE);
int s = now.get(Calendar.SECOND);
Clock.this.setText("" + h + ":" + m + ":" + s);
}
});
t.start(); // Start the timer
}//end constructor
}//end class Clock |