JavaFX

JavaFX Animation Example

The Animation class provides the core functionality of all animations used in the JavaFX. This abstract class is defined in javafx.animation package.

1. Overview

The following are the main properties of Animation:

  • Cycle count: Defines the number of cycles in this animation. The cycleCount may be INDEFINITE for animations that repeat indefinitely, but must otherwise be > 0.
  • Auto reverse: Defines whether this Animation reverses direction on alternating cycles.

The methods play() or playFromStart() are used to play an Animation. An animation can be paused by calling pause(), and the next play() call will resume the animation from where it was paused.

Animation has two direct subclasses: Transition and Timeline. These two classes are defined in the javax.animation package.

1.1. Transition

This class contains the basic functionality required by all Transition based animations. The following are its subclasses:

  • FadeTransition: This Transition creates a fade effect animation that spans its duration.
  • FillTransition: This Transition creates an animation, which changes the filling of a shape over a duration.
  • ParallelTransition: This Transition plays a list of animations in parallel.
  • PathTransition: This Transition creates a path animation that spans its duration.
  • PauseTransition: This Transition executes an Animation.onFinished at the end of its duration.
  • RotateTransition: This Transition creates a rotation animation.
  • ScaleTransition: This Transition creates a scale animation that spans its duration.
  • SequentialTransition: This Transition plays a list of animations in sequential order.
  • StrokeTransition: This Transition creates an animation, which changes the stroke color of a shape over a duration.
  • TranslateTransition: This Transition creates a move/translate animation that spans its duration.

These are all defined in the javafx.animation package.

1.2. Timeline

A Timeline can be used to define a free form animation of any WritableValue, e.g. all JavaFX Properties (defined as Property interface). A Timeline, defined by one or more Key Frames, processes individual KeyFrame sequentially, in the order specified by KeyFrame.time. The animated properties are defined as key values in KeyFrame.values.

1.3. Examples

This article has examples showing Transition and the Timeline class usage.

The Transition example demonstrates the usage of FillTransition, PathTransition and ParallelTransition (this uses FadeTransition and RotateTransition).

2. Transition Animation Example

This example shows the usage of Transition animation’s API. The following GUI shown the example’s main window:

TransitionAnimationExample
TransitionAnimationExample

From the GUI click a button to see the demonstration of that transition animation.

2.1. Fill Transition

The following code snippet shows the code to create and play the animation:

Group root = new Group();
Circle circle = new Circle(100, 100, 50);
root.getChildren().add(circle);
Scene scene = new Scene(root, 200, 200);
stage.setScene(scene);
stage.show();
		
FillTransition ft = new FillTransition(Duration.millis(3000), circle, Color.RED, Color.YELLOW);

ft.setCycleCount(4);
ft.setAutoReverse(true);
ft.play();

The FillTransition creates an animation, that changes the filling of a Shape over a Duration. This is done by updating the fill variable of the shape at regular intervals. The shape used is a Circle. This is filled with Color red initially and transitions to yellow. The duration of the transition is set as 3000 millis.

The FillTransition is created using the constructor with the duration, shape, from and to color values.

The Animation‘s setCycleCount() method defines four cycles and the setAutoReverse() method specifies that animation reverses direction on alternating cycles. Note that animation stops automatically after four cycles.

The following images shows the circle’s fill transitioning from start color to end color.

FillTransitonStart
FillTransitonStart

FillTransitonEnd
FillTransitonEnd

2.2. Path Transition

The following code snippet shows the code to create and play the animation:

Group root = new Group();
Circle circle = new Circle(20, Color.LIGHTCORAL);
root.getChildren().add(circle);
			
Path path = new Path();
path.getElements().addAll(new MoveTo(50, 50), new HLineTo(350));
path.setFill(null);
root.getChildren().add(path);
			
Scene scene = new Scene(root, 400, 100);
stage.setScene(scene);
stage.show();
			
PathTransition pt = new PathTransition(Duration.millis(4000), path, circle);
pt.setCycleCount(Animation.INDEFINITE);
pt.setAutoReverse(true);
pt.play();

The PathTransition creates a path animation that spans its Duration. The translation along the Path is done by updating the translateX and translateY variables of the Node, and the rotate variable will get updated if orientation is set to OrientationType.ORTHOGONAL_TO_TANGENT, at regular interval. The animated path is defined by the outline of a Shape.

In the example, the shape used is a Circle and the Path a horizontal line. The PathTransition is created using the constructor with the duration, path and the shape.

The circle animates along the horizontal line path for the duration for each cycle. Note the values set for duration, cycle count and auto reverse properties.

The following images show the circle animating on the path.

PathTransiton1
PathTransiton1

PathTransiton2
PathTransiton2

2.3. Parallel Transition

The following code snippet shows the code to create and play the animation:

Group root = new Group();
			
Rectangle rect = new Rectangle(100, 100, 100, 100);
rect.setFill(Color.BLUE);
root.getChildren().add(rect);
			
FadeTransition ft = new FadeTransition(Duration.millis(3000));
ft.setFromValue(1);
ft.setToValue(0.1);
ft.setCycleCount(Animation.INDEFINITE);
ft.setAutoReverse(true);
			
RotateTransition rt = new RotateTransition(Duration.seconds(5));
rt.setByAngle(180);
rt.setCycleCount(Animation.INDEFINITE);
rt.setAutoReverse(true);
			
Scene scene = new Scene(root, 300, 300);
stage.setScene(scene);
stage.show();
			
ParallelTransition pt = new ParallelTransition(rect, ft, rt);
pt.play();

ParallelTransition plays a list of Animations in parallel. The example uses FadeTransition and RotateTransition. These are applied to a Rectangle Shape with Color blue which is the target Node.

FadeTransition creates a fade effect animation that spans its Duration. This is done by updating the opacity variable of the node at regular interval. In the example, the opacity from and to values are specified using the FadeTransition methods setFromValue() and setToValue() respectively. In the above code, the transition is created using the duration and the opacity values.

RotateTransition creates a rotation animation that spans its duration. This is done by updating the rotate variable of the node at regular interval. The angle value is specified in degrees by the RotateTransition‘s setByAngle() method. In the above code, the transition is created using the duration and the by angle values.

The ParallelTransition is created and played using the rectangle node and the two child transition animations. The animation shows a blue colored rectangle that rotates to 180 degrees and in reverse every 5 second duration while the color fades to and fro.

The following images show the transition:

ParallelTransition1
ParallelTransition1

ParallelTransition2
ParallelTransition2

3. Timeline Animation Example

The following code snippet shows the code to create and play the animation:

Circle circle = new Circle(100, 100, 20);

VBox vbox = new VBox(30);
vbox.setPadding(new Insets(25, 25, 25, 25));

Timeline timeline = new Timeline();
			
Text currTimeText = new Text("Current time: 0 secs" );
currTimeText.setBoundsType(TextBoundsType.VISUAL);
			
timeline.currentTimeProperty().addListener(new InvalidationListener() {
			
    public void invalidated(Observable ov) {
				
        int time = (int) timeline.getCurrentTime().toSeconds();
        currTimeText.setText("Current time: " + time + " secs");
    }
});
	
vbox.getChildren().addAll(circle, currTimeText);
			
Scene scene = new Scene(vbox, 500, 100);
stage.setScene(scene);
stage.show();

Duration time = new Duration(10000);
KeyValue keyValue = new KeyValue(circle.translateXProperty(), 300);
KeyFrame keyFrame = new KeyFrame(time, keyValue);
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(2);
timeline.setAutoReverse(true);
timeline.play();

The above code shows creating a simple Timeline. This timeline will run for 20 seconds, animating the node by x axis to value 300 and then back to 0 on the second cycle. The example when run, displays the following window with the circle animating on a horizontal line and the time elapsed as it moves through the two cycles.

The KeyFrame, KeyValue and Duration are the main API used in Timeline‘s construction.

TimelineAnimation
TimelineAnimation

4. Download Java Source Code

This was an example of javafx.animation.Animation

Download
You can download the full source code of this example here: AnimationExamples.zip

Prasad Saya

Prasad Saya is a software engineer with over ten years’ experience in application development, maintenance, testing and consulting on various platforms. He is a certified Java and Java EE developer. At present his interest is in developing Java applications. He also has experience working with databases and ERP applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button