public class TimerTest
class TimerTestFrame extends JFrame
class ClockCanvas extends JPanel
1: /**
2: @version 1.21 2003-09-09
3: @author Cay Horstmann
4: */
5:
6: import java.awt.*;
7: import java.awt.event.*;
8: import javax.swing.*;
9: import java.util.*;
10: import javax.swing.Timer;
11:
12: /**
13: This class shows a frame with several clocks that
14: are updated by a timer thread.
15: */
16: public class TimerTest
17: {
18: public static void main(String[] args)
19: {
20: TimerTestFrame frame = new TimerTestFrame();
21: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22: frame.setVisible(true);
23: }
24: }
25:
26: /**
27: The frame holding the clocks.
28: */
29: class TimerTestFrame extends JFrame
30: {
31: public TimerTestFrame()
32: {
33: setTitle("TimerTest");
34: setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
35:
36: Container c = getContentPane();
37: c.setLayout(new GridLayout(2, 3));
38: c.add(new ClockCanvas("America/Los_Angeles"));
39: c.add(new ClockCanvas("America/New_York"));
40: c.add(new ClockCanvas("America/Caracas"));
41: c.add(new ClockCanvas("Europe/Rome"));
42: c.add(new ClockCanvas("Africa/Cairo"));
43: c.add(new ClockCanvas("Asia/Taipei"));
44: }
45:
46: public static final int DEFAULT_WIDTH = 450;
47: public static final int DEFAULT_HEIGHT = 300;
48: }
49:
50: /**
51: The canvas to display a clock that is updated by a timer.
52: */
53: class ClockCanvas extends JPanel
54: {
55: /**
56: Constructs a clock canvas.
57: @param tz the time zone string
58: */
59: public ClockCanvas(String tz)
60: {
61: zone = tz;
62: calendar = new GregorianCalendar(TimeZone.getTimeZone(tz));
63: Timer t = new Timer(1000, new
64: ActionListener()
65: {
66: public void actionPerformed(ActionEvent event)
67: {
68: calendar.setTime(new Date());
69: repaint();
70: }
71: });
72: t.start();
73: setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
74: }
75:
76: public void paintComponent(Graphics g)
77: {
78: super.paintComponent(g);
79: g.drawOval(0, 0, 100, 100);
80:
81: int seconds = calendar.get(Calendar.HOUR) * 60 * 60
82: + calendar.get(Calendar.MINUTE) * 60
83: + calendar.get(Calendar.SECOND);
84: double hourAngle = 2 * Math.PI
85: * (seconds - 3 * 60 * 60) / (12 * 60 * 60);
86: double minuteAngle = 2 * Math.PI
87: * (seconds - 15 * 60) / (60 * 60);
88: double secondAngle = 2 * Math.PI
89: * (seconds - 15) / 60;
90: g.drawLine(50, 50, 50 + (int)(30
91: * Math.cos(hourAngle)),
92: 50 + (int)(30 * Math.sin(hourAngle)));
93: g.drawLine(50, 50, 50 + (int)(40
94: * Math.cos(minuteAngle)),
95: 50 + (int)(40 * Math.sin(minuteAngle)));
96: g.drawLine(50, 50, 50 + (int)(45
97: * Math.cos(secondAngle)),
98: 50 + (int)(45 * Math.sin(secondAngle)));
99: g.drawString(zone, 0, 115);
100: }
101:
102: private String zone;
103: private GregorianCalendar calendar;
104:
105: public static final int DEFAULT_WIDTH = 125;
106: public static final int DEFAULT_HEIGHT = 125;
107: }