Java Reference
In-Depth Information
15.11.3 Timeline
PathTransition and FadeTransition define specialized animations. The Timeline
class can be used to program any animation using one or more KeyFrame s. Each KeyFrame
is executed sequentially at a specified time interval. Timeline inherits from Animation .
You can construct a Timeline using the constructor new Timeline(KeyFrame...
keyframes) . A KeyFrame can be constructed using
new KeyFrame(Duration duration, EventHandler<ActionEvent> onFinished)
The handler onFinished is called when the duration for the key frame is elapsed.
ListingĀ 15.15 gives an example that displays a flashing text, as shown in FigureĀ 15.20. The
text is on and off alternating to animate flashing.
L ISTING 15.15
TimelineDemo.java
1 import javafx.animation.Animation;
2 import javafx.application.Application;
3 import javafx.stage.Stage;
4 import javafx.animation.KeyFrame;
5 import javafx.animation.Timeline;
6 import javafx.event.ActionEvent;
7 import javafx.event.EventHandler;
8 import javafx.scene.Scene;
9 import javafx.scene.layout.StackPane;
10 import javafx.scene.paint.Color;
11 import javafx.scene.text.Text;
12 import javafx.util.Duration;
13
14 public class TimelineDemo extends Application {
15 @Override // Override the start method in the Application class
16 public void start(Stage primaryStage) {
17 StackPane pane = new StackPane();
18 Text text = new Text( 20 , 50 , "Programming is fun" );
19 text.setFill(Color.RED);
20
VideoNote
Flashing text
create a stack pane
create a text
pane.getChildren().add(text); // Place text into the stack pane
add text to pane
21
22
// Create a handler for changing text
23
EventHandler<ActionEvent> eventHandler = e -> {
handler for changing text
24
if (text.getText().length() != 0 ) {
25
text.setText( "" );
set text empty
26
}
27
else {
28
text.setText( "Programming is fun" );
set text
29
}
30
};
31
32 // Create an animation for alternating text
33 Timeline animation = new Timeline(
34 new KeyFrame(Duration.millis( 500 ), eventHandler));
35 animation.setCycleCount(Timeline.INDEFINITE);
36 animation.play(); // Start animation
37
38 // Pause and resume animation
39 text.setOnMouseClicked(e -> {
40 if (animation.getStatus() == Animation.Status.PAUSED) {
41 animation.play();
42 }
43 else {
44 animation.pause();
create a Timeline
create a KeyFrame for handler
set cycle count indefinite
play animation
resume animation
pause animation
 
 
Search WWH ::




Custom Search