Back to Java
2026-02-248 min read

Introduction to JavaFX animations

Learn Introduction to JavaFX animations step by step with clear examples and exercises.

Why This Matters

JavaFX animations are an essential aspect of modern UI design, providing a means to create engaging, interactive, and visually appealing applications. By learning how to use JavaFX animations, developers can enhance the user experience, provide feedback, and align with current design principles. In this lesson, we will delve into the basics of creating animations in JavaFX, exploring various aspects such as transitions, timelines, keyframes, and custom animations.

Why This Matters

Animations play a crucial role in modern UI design. They can help guide users through complex interfaces, provide feedback, create a more engaging user experience, and contribute to the overall aesthetic appeal of an application. JavaFX offers a simple yet powerful framework for creating animations that can be applied to various UI elements like shapes, images, and controls.

Prerequisites

Before diving into JavaFX animations, it is essential to have a basic understanding of:

  • The Java programming language
  • JavaFX basics (layouts, controls, etc.)

It is also beneficial to be familiar with the following JavaFX packages:

  • javafx.scene.layout
  • javafx.scene.paint
  • javafx.scene.shape
  • javafx.animation

Core Concept

The javafx.animation package offers a simple yet powerful framework for creating animations and transitions in a JavaFX application. It operates on the principle of WritableValue, which is used across JavaFX to store properties in UI elements like width or height in the Rectangle shape.

Animation

The abstract class Animation provides the core functionality for Transition and Timeline animations and can't be extended directly. An Animation consists of multiple properties:

  • targetFramerate: The maximum framerate (frames per second) at which this Animation will run.
  • currentTime: The current point in time in the Animation as a Duration.
  • rate: Defines the direction and speed at which the Animation is expected to be played. It supports both positive and negative numbers.
  • cycleCount: Defines the number of cycles of this Animation. It can't be changed while running and must be positive.
  • cycleDuration: The Duration of one cycle of this Animation. It is the time it takes to play from start to end of the Animation at the default rate of 1.0.
  • totalDuration: Indicates the total duration of this Animation, including repeats. It is the result of cycleDuration * cycleCount or possibly Duration.INDEFINITE.
  • delay: The Duration that delays the Animation when starting.
  • autoReverse: Specifies whether the Animation will play in reverse direction on alternating cycles.
  • onFinished: Event handler used to define additional behavior when the Animation finished.
  • status: Represents the current state of the Animation, possible states are PAUSED, RUNNING, and STOPPED.

Additionally, it provides several useful methods, like play(), playFrom(String cuePoint), pause(), stop(), and more to control the animations flow.

Transition

Transition is a subclass of Animation that provides a simpler and more user-friendly way to create animations. It offers built-in transitions for common effects, support for parallel and sequential transitions, and the ability to handle events upon animation completion.

Common Transitions

JavaFX provides several predefined transition types:

  1. FadeTransition: Fades an element in or out.
  2. ScaleTransition: Scales an element up or down.
  3. RotateTransition: Rotates an element around a specific pivot point.
  4. ParallelTransition: Allows multiple transitions to play simultaneously.
  5. SequenceTransition: Allows multiple transitions to play one after another.

Timeline

A Timeline is a sequence of keyframes that define how an animation's properties change over time. It can be thought of as a custom animation created by combining various keyframes.

Keyframe

Keyframes are used to define the values of an animation property at specific points in time. Each keyframe consists of:

  • time: The point in time when the keyframe's value should be applied.
  • value: The new value for the animation property at the specified time.

Worked Example

Let's create a simple example where we animate the size and color of a Rectangle from 100x100 with red color to 200x200 with blue color over a duration of 5 seconds.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.animation.*;
import javafx.util.Duration;
import javafx.stage.Stage;

public class AnimationExample extends Application {
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
Rectangle rectangle = new Rectangle(100, 100, Color.RED);
root.getChildren().add(rectangle);

Timeline timeline = createSizeAndColorAnimation(rectangle, 5.0);
timeline.play();

primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.show();
}

private Timeline createSizeAndColorAnimation(Rectangle rectangle, double duration) {
KeyValue kvWidth = new KeyValue(rectangle.widthProperty(), 200);
KeyValue kvHeight = new KeyValue(rectangle.heightProperty(), 200);
KeyValue kvFill = new KeyValue(rectangle.fillProperty(), Color.BLUE);

KeyFrame kfWidth = new KeyFrame(Duration.seconds(0), new KeyValue(rectangle.widthProperty(), 100));
KeyFrame kfHeight = new KeyFrame(Duration.seconds(2.5), kvHeight);
KeyFrame kfFill = new KeyFrame(Duration.seconds(3), kvFill);
KeyFrame kfEnd = new KeyFrame(Duration.seconds(5), new KeyValue(rectangle.widthProperty(), 200));

Timeline timeline = new Timeline();
timeline.getKeyFrames().addAll(kfWidth, kfHeight, kfFill, kfEnd);
timeline.setCycleCount(Animation.INDEFINITE);
return timeline;
}

public static void main(String[] args) {
launch(args);
}
}

In this example, we create a Rectangle with an initial width and height of 100 and set its color to red. We then create a separate method called createSizeAndColorAnimation() that creates the Timeline animation with four keyframes: one at the start (duration 0 seconds), one after 2.5 seconds (changing the width and height to 200), another at 3 seconds (changing the fill color to blue), and a final keyframe at 5 seconds (setting the width back to 200). Finally, we add the rectangle to a StackPane, create a scene with it, set the stage, and show the application.

Common Mistakes

  • Forgetting to call play() on the Timeline: The animation will not start if you forget to call play() on the Timeline.
  • To avoid this mistake, make sure to always call play() after setting up your animation and before showing the application.
  • Setting cycleCount to a negative value: The cycle count must be positive or zero. Negative values are not allowed.
  • When defining the number of cycles for an animation, ensure that it is set to a positive value or zero.
  • Using incorrect units for width and height properties: Make sure to use pixels (px) as the unit when setting the width and height properties of UI elements.
  • Always use pixels (px) as the unit when working with the width and height properties of UI elements.
  • Not handling the onFinished event: You can define additional behavior when the animation finishes by setting an onFinished event handler.
  • To handle the onFinished event, create an event handler and set it as the value for the onFinished property of your animation.
  • Forgetting to add keyframes for all properties being animated: Make sure to create a keyframe for each property you want to animate, such as width, height, and fill color in our example above.
  • When creating animations, ensure that you have a keyframe for each property being animated.
  • Setting the targetFramerate too high: Setting a high targetFramerate can lead to performance issues, especially on lower-end hardware.
  • To avoid performance issues, set a reasonable targetFramerate, taking into account the capabilities of the target hardware.

Practice Questions

  1. Create an animation that changes the color of a Circle from red to blue over a duration of 3 seconds.
  • To create this animation, you can use the FadeTransition for changing the color of the circle and set its duration to 3 seconds.
  1. Create an animation that moves a Rectangle from (50, 50) to (200, 200) over a duration of 4 seconds while scaling it up by a factor of 2.
  • To create this animation, you can use the ParallelTransition with a combination of TranslateTransition and ScaleTransition. Set the duration to 4 seconds and adjust the properties accordingly.
  1. Create an animation that rotates a Polygon 360 degrees over a duration of 10 seconds.
  • To create this animation, you can use the RotateTransition with a duration of 10 seconds and set the angleFrom and angleTo properties to 0 and 360 respectively.
  1. Create an animation that shrinks a Square from its current size to half its size over a duration of 2 seconds.
  • To create this animation, you can use the ScaleTransition with a duration of 2 seconds and set the scaleX and scaleY properties to 0.5 at the end keyframe.
  1. Create an animation that fades out a Text element over a duration of 3 seconds and then fades it back in over another 3 seconds.
  • To create this animation, you can use the SequenceTransition with two FadeTransition instances. Set the first fade transition's duration to 3 seconds and the second one's duration to another 3 seconds, making sure that the second fade transition starts at the end of the first one.

FAQ

  1. Can I create custom animations in JavaFX? Yes, you can create custom animations by extending the Animation class and implementing the required methods.
  • To create a custom animation, extend the Animation class and override its required methods such as interpolate(), playFromStart(), and playToEnd().
  1. How do I pause an animation in JavaFX? You can pause an animation by calling the pause() method on the Animation or Timeline.
  • To pause an animation, call the pause() method on the Animation or Timeline object.
  1. Can I use JavaFX animations with other UI libraries like Swing? No, JavaFX animations are specific to the JavaFX UI library and cannot be used with other UI libraries such as Swing.
  • JavaFX animations are not compatible with other UI libraries like Swing, as they are designed specifically for use within the JavaFX framework.
  1. What is the difference between a Timeline and a Transition in JavaFX animations? A Timeline is a sequence of keyframes that define how an animation's properties change over time, while a Transition is a predefined animation type (like Fade or Scale) provided by JavaFX.
  • A Timeline is a custom animation created by combining various keyframes, whereas a Transition is a predefined animation type offered by JavaFX for common effects like fading and scaling.
  1. How do I create a custom Transition in JavaFX? To create a custom transition, you can extend the Transition class and override its required methods such as interpolate(), playFromStart(), and playToEnd().
  • To create a custom transition, extend the Transition class and implement its required methods like interpolate(), playFromStart(), and playToEnd(). This will allow you to define your own animation behavior.
Introduction to JavaFX animations | Java | XQA Learn