Java Reference
In-Depth Information
5
public
DisplayClock() {
6
// Create an analog clock for the current time
7
8
9
StillClock clock =
new
StillClock();
create a clock
// Display hour, minute, and second in the message panel
MessagePanel messagePanel =
new
MessagePanel(clock.getHour() +
10
11
12 messagePanel.setCentered(
true
);
13 messagePanel.setForeground(Color.blue);
14 messagePanel.setFont(
new
Font(
"Courier"
, Font.BOLD,
16
));
15
16
// Add the clock and message panel to the frame
17 add(clock);
18 add(messagePanel, BorderLayout.SOUTH);
19 }
20
21
public static void
main(String[] args) {
22 DisplayClock frame =
new
DisplayClock();
23 frame.setTitle(
"DisplayClock"
);
24 frame.setSize(
300
,
350
);
25 frame.setLocationRelativeTo(
null
);
// Center the frame
26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 frame.setVisible(
true
);
28 }
29 }
create a message panel
":"
+ clock.getMinute() +
":"
+ clock.getSecond());
add a clock
add a message panel
(0, 0)
(xEnd, yEnd)
12
handLength
9
3
(xCenter, yCenter)
6
(a)
(b)
F
IGURE
13.21
(a) The
DisplayClock
program displays a clock that shows the current
time. (b) The endpoint of a clock hand can be determined, given the spanning angle, the
hand length, and the center point.
The rest of this section explains how to implement the
StillClock
class. Since you can use
the class without knowing how it is implemented, you may skip the implementation if you
wish.
To draw a clock, you need to draw a circle and three hands for the second, minute, and
hour. To draw a hand, you need to specify the two ends of the line. As shown in Figure
13.21b, one end is the center of the clock at
(xCenter, yCenter)
; the other end, at
(xEnd, yEnd)
, is determined by the following formula:
skip implementation?
implementation
xEnd = xCenter + handLength
×
sin(
θ
)
yEnd = yCenter - handLength
×
cos(
θ
)
Since there are 60 seconds in one minute, the angle for the second hand is
second
×
(2
π
/60)