Java Reference
In-Depth Information
L ISTING 14.20
DisplayClock.java
1 import javafx.application.Application;
2 import javafx.geometry.Pos;
3 import javafx.stage.Stage;
4 import javafx.scene.Scene;
5 import javafx.scene.control.Label;
6 import javafx.scene.layout.BorderPane;
7
8 public class DisplayClock extends Application {
9 @Override // Override the start method in the Application class
10 public void start(Stage primaryStage) {
11 // Create a clock and a label
12 ClockPane clock = new ClockPane();
13 String timeString = clock.getHour() + " : " + clock.getMinute()
14 + " : " + clock.getSecond();
15
create a clock
Label lblCurrentTime = new Label(timeString);
create a label
16
17 // Place clock and label in border pane
18 BorderPane pane = new BorderPane();
19 pane.setCenter(clock);
20 pane.setBottom(lblCurrentTime);
21 BorderPane.setAlignment(lblCurrentTime, Pos.TOP_CENTER);
22
23 // Create a scene and place it in the stage
24 Scene scene = new Scene(pane, 250 , 250 );
25 primaryStage.setTitle( " DisplayClock " ); // Set the stage title
26 primaryStage.setScene(scene); // Place the scene in the stage
27 primaryStage.show(); // Display the stage
28 }
29 }
add a clock
add a label
The rest of this section explains how to implement the ClockPane 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 14.42b, one
end is the center of the clock at (centerX, centerY) ; the other end, at (endX, endY) , is
determined by the following formula:
skip implementation?
implementation
endX = centerX + handLength × sin( θ )
endY = centerY - handLength × cos( θ )
Since there are 60 seconds in one minute, the angle for the second hand is
second × (2π/60)
The position of the minute hand is determined by the minute and second. The exact minute
value combined with seconds is minute + second/60 . For example, if the time is 3 minutes
and 30 seconds, the total minutes are 3.5. Since there are 60 minutes in one hour, the angle
for the minute hand is
(minute + second/60) × (2π/60)
Since one circle is divided into 12 hours, the angle for the hour hand is
(hour + minute/60 + second/(60 × 60)) × (2π/12)
 
 
Search WWH ::




Custom Search