Chapter 7 |
Animations
JavaFX also allows to create animations. The abstract Animation
class provides core functionalities for animations in JavaFX. For more information about particular classes, methods, or additional features see the API documentation.
Useful link:
Examples of animations can be found here
.
Coming back to the scene graph, all previous examples were about leaf nodes. Concerning the root, we have tried to add some elements to it. The following example demonstrates manipulations with the root. FadeTransition
is a subclass of Animation
. In the following example, FadeTransition
animates the opacity of the root with a rectangle and a button inside using a fade transition. A fade transition is created with a duration of 10 seconds for the root (Line 11). It sets the start opaque to 1.0 (Line 12) and the stop opaque 0.0 (Line 13). The cycle count is set to the infinity; therefore, the animation is repeated indefinitely (Line 14).
public void start(Stage primaryStage) { Group root = new Group(); // create the root node Rectangle rectangle1 = new Rectangle(50, 50, 435, 435); Button ok = new Button("OK"); ok.setLayoutX(10); ok.setLayoutY(10); root.getChildren().add(ok); // place a button on the scene root.getChildren().add(rectangle1); // place a rectangle on the scene // Apply a fade transition to the root FadeTransition ft = new FadeTransition(Duration.millis(10000), root); ft.setFromValue(1.0); ft.setToValue(0.0); ft.setCycleCount(Timeline.INDEFINITE); ft.setAutoReverse(true); ft.play(); // start the animation Scene scene1 = new Scene(root, 535, 535, Color.SNOW); // create a scene primaryStage.setTitle("Black square"); // set stage title primaryStage.setScene(scene1); // place the scene on the stage primaryStage.show(); // display the stage }
Try out
Compile and run the code above.
Add some shapes (Shape
subclass object) and try to make the shape move (animate) along the path from one end to the other using PathTransition
class.
Next, try to display several animations simultaniously using Parallel Transition
and Sequential Transition
classes.
Chapter 7 |