19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

13.9 Case Study: The StillClock Class 501<br />

5 public DisplayClock() {<br />

6 // Create an analog clock for the current time<br />

7 StillClock clock = new StillClock();<br />

8<br />

9 // Display hour, minute, and second in the message panel<br />

10 MessagePanel messagePanel = new MessagePanel(clock.getHour() +<br />

11 ":" + clock.getMinute() + ":" + clock.getSecond());<br />

12 messagePanel.setCentered(true);<br />

13 messagePanel.setForeground(Color.blue);<br />

14 messagePanel.setFont(new Font("Courier", Font.BOLD, 16));<br />

15<br />

16 // Add the clock and message panel <strong>to</strong> the frame<br />

17 add(clock);<br />

18 add(messagePanel, BorderLayout.SOUTH);<br />

19 }<br />

20<br />

21 public static void main(String[] args) {<br />

22 DisplayClock frame = new DisplayClock();<br />

23 frame.setTitle("DisplayClock");<br />

24 frame.setSize(300, 350);<br />

25 frame.setLocationRelativeTo(null); // Center the frame<br />

26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />

27 frame.setVisible(true);<br />

28 }<br />

29 }<br />

create a clock<br />

create a message panel<br />

add a clock<br />

add a message panel<br />

(0, 0)<br />

(xEnd, yEnd)<br />

12<br />

handLength<br />

9 3<br />

(xCenter, yCenter)<br />

6<br />

(a)<br />

FIGURE 13.21 (a) The DisplayClock program displays a clock that shows the current<br />

time. (b) The endpoint of a clock hand can be determined, given the spanning angle, the<br />

hand length, and the center point.<br />

(b)<br />

The rest of this section explains how <strong>to</strong> implement the StillClock class. Since you can use<br />

the class without knowing how it is implemented, you may skip the implementation if you<br />

wish.<br />

To draw a clock, you need <strong>to</strong> draw a circle and three hands for the second, minute, and<br />

hour. To draw a hand, you need <strong>to</strong> specify the two ends of the line. As shown in Figure<br />

13.21b, one end is the center of the clock at (xCenter, yCenter); the other end, at<br />

(xEnd, yEnd), is determined by the following formula:<br />

skip implementation?<br />

implementation<br />

xEnd = xCenter + handLength × sin(θ)<br />

yEnd = yCenter - handLength × cos(θ)<br />

Since there are 60 seconds in one minute, the angle for the second hand is<br />

second × (2π/60)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!