Java Reference
In-Depth Information
45 }
46 });
47
48 // Create a scene and place it in the stage
49 Scene scene = new Scene(pane, 250 , 250 );
50 primaryStage.setTitle( "TimelineDemo" ); // Set the stage title
51 primaryStage.setScene(scene); // Place the scene in the stage
52 primaryStage.show(); // Display the stage
53 }
54 }
F IGURE 15.20
The handler is called to set the text to Programming is fun or empty in turn.
The program creates a stack pane (line 17) and a text (line 18) and places the text into the pane
(line 20). A handler is created to change the text to empty (lines 24-26) if it is not empty or
to Progrmming is fun if it is empty (lines 27-29). A KeyFrame is created to run an action
event in every half second (line 34). A Timeline animation is created to contain a key frame
(lines 33 and 34). The animation is set to run indefinitely (line 35).
The mouse clicked event is set for the text (lines 39-46). A mouse click on the text resumes
the animation if the animation is paused (lines 40-42), and a mouse click on the text pauses
the animation if the animation is running (lines 43-45).
In Section 14.12, Case Study: The ClockPane Class, you drew a clock to show the current
time. The clock does not tick after it is displayed. What can you do to make the clock display a
new current time every second? The key to making the clock tick is to repaint it every second
with a new current time. You can use a Timeline to control the repainting of the clock with
the code in Listing 15.16. The sample run of the program is shown in Figure 15.21.
L ISTING 15.16
ClockAnimation.java
1 import javafx.application.Application;
2 import javafx.stage.Stage;
3 import javafx.animation.KeyFrame;
4 import javafx.animation.Timeline;
5 import javafx.event.ActionEvent;
6 import javafx.event.EventHandler;
7 import javafx.scene.Scene;
8 import javafx.util.Duration;
9
10 public class ClockAnimation extends Application {
11 @Override // Override the start method in the Application class
12
public void start(Stage primaryStage) {
13
ClockPane clock = new ClockPane(); // Create a clock
create a clock
14
15
// Create a handler for animation
16
EventHandler<ActionEvent> eventHandler = e -> {
create a handler
17
clock.setCurrentTime(); // Set a new clock time
18
};
19
20 // Create an animation for a running clock
21 Timeline animation = new Timeline(
create a time line
 
 
Search WWH ::




Custom Search