JavaFX Animation Features

JavaFX includes many animation features. Let’s use classes such as Transition and Timeline to move graphics.

Using TranslateTransition

One area where JavaFX is stronger than Swing is animation. In Swing, animating graphics required creating threads and timers, repeatedly moving positions and repainting. In JavaFX, animation can be created much more easily.

Animation-related features are provided in the javafx.animation package. First, let’s use the most common one: moving the display position.

This is provided by the TranslateTransition class. It is one of the most basic animation classes. Once you understand this class, other animation classes can be handled in much the same way.

Create a TranslateTransition instance as follows.

new TranslateTransition();
new TranslateTransition("Duration");
new TranslateTransition("Duration", "Node");

There are several constructors, from one with no arguments to ones that take Duration and Node. Node is the instance of the part to move. For graphics, specify a shape-related instance here.

Duration is a class in the javafx.util package and is used to handle animation elapsed time. Create an instance as follows.

new Duration(milliseconds);

This creates a Duration instance that represents the elapsed time specified in milliseconds. This gives you the basic animation setting: which shape moves over what amount of time.

If you do not pass Node and Duration as constructor arguments, you must set them later with methods.

"TranslateTransition".setNode ( "Node");
"TranslateTransition".setDuration ( "Duration");

Without these, there is no animation, so it is usually better to specify them as constructor arguments from the beginning.

Animation Setting Methods

After creating a TranslateTransition instance, call methods to configure the details of the animation. Many methods are available, but the basic ones are as follows.

Methods for setting the position before movement

"TranslateTransition".setFromX("double");
"TranslateTransition".setFromY("double");
"TranslateTransition".setFromZ("double");

Methods for setting the destination position

"TranslateTransition".setToX("double");
"TranslateTransition".setToY("double");
"TranslateTransition".setToZ("double");

Auto reverse setting

"TranslateTransition".setAutoReverse("boolean");

Repeat count setting

"TranslateTransition".setCycleCount ( "int");

After roughly configuring these settings, call the play method of TranslateTransition to start the animation. Methods such as stop and pause are also provided for stopping or pausing during playback. They are simply called without arguments.

A simple example is as follows.

// import javafx.animation.*;
// import javafx.util.Duration;
 
public void createShape(Pane root){
    Rectangle r = new Rectangle(20, 20, 50, 50);
    r.setFill(Color.CYAN);
    root.getChildren().add(r);
    new TranslateTransition();
     
    TranslateTransition tt = new TranslateTransition(new Duration(1000), r);
    tt.setFromX(20);
    tt.setToX(100);
    tt.setAutoReverse(true);
    tt.setCycleCount(10);
    tt.play();
}

This rewrites the createShape method used earlier for creating shapes. When you run it, the visible rectangle moves back and forth horizontally.

Main Animation Classes

There are many animation classes besides TranslateTransition. The important ones are summarized here.

Resize Animation

new ScaleTransition("Duration", "Node");

Setting methods

"ScaleTransition".setFromX("double");
"ScaleTransition".setFromY("double");
"ScaleTransition".setFromZ("double");

"ScaleTransition".setToX("double");
"ScaleTransition".setToY("double");
"ScaleTransition".setToZ("double");

Rotation Animation

new RotateTransition ( "Duration", "Node");

Setting methods

"RotateTransition".setFromAngle ( "double");
"RotateTransition".setToAngle ( "double");

Color Animation

new FillTansition("Duration", "Node");
new FillTansition("Duration", "Node", "Color1", "Color2");

new StrokeTransition("Duration", "Node");
new StrokeTransition("Duration", "Node", "Color1", "Color2");

Setting methods

"StrokeTransition".setFromValue("Color");
"StrokeTransition".setToValue("Color");

Fade Animation

new FadeTransition("Duration", "Node");

Setting methods

"FadeTransition".setFromValue("double");
"FadeTransition".setToValue("double");

The basic usage is the same as TranslateTransition: create an instance with Duration and Node, call methods to set the values before and after the animation, adjust settings such as setAutoReverse and cycle count, and start it with play.

Once you can use TranslateTransition, you can use these classes with almost the same feeling.

Using Timeline

The classes above are basically for creating smooth animations that change from a current state to a next state. Chaining several of them together is not efficient when you want more complex movement.

For those cases, use the Timeline class. As the name suggests, Timeline is an animation timeline that manages changes over time.

To use Timeline, you need the KeyFrame class. It represents a key frame set on the timeline, meaning a specific animation state at a specific time.

Create a Timeline instance first, then add KeyFrame instances as needed. After the required settings are complete, start the animation with play. The necessary pieces are summarized below.

Creating a Timeline

new Timeline();

Create a Timeline instance with the default constructor. Unlike the previous animation classes, it does not directly set Node or Duration.

Creating a KeyFrame

new KeyFrame("Duration", "KeyValue");

KeyFrame takes Duration and KeyValue instances as arguments. Duration is the animation playback time object introduced earlier.

KeyValue is a class that handles a value set for a key. It is created as follows.

Creating a KeyValue

new keyValue("Property value");

KeyValue takes a class that implements the Property interface and the value to set on it as arguments. Most shape properties are created by implementing the Property interface, and methods are provided to retrieve Property instances representing those properties. Use those methods to create a KeyValue from the target shape property and the value to set.

This prepares the Timeline, KeyFrame, and KeyValue needed for animation. Next, assemble the animation information from them.

Showing Animation with Timeline

The created Timeline provides various methods for animation settings. Use them to assemble the needed information. The main methods are listed below.

Auto Reverse Setting

"Timeline".setAutoReverse("boolean");

This plays the animation back and forth. Set it to true to enable auto reverse.

Playback Count Setting

"Timeline".setCycleCount("int");

Specify the number of times the animation plays as an integer.

Getting the List That Manages KeyFrames

"Timeline".getKeyFrames ();

The KeyFrame instances set on Timeline are stored in a List (ObservableList) instance. Use getKeyFrames to retrieve this list.

Adding a KeyFrame

"ObservableList".add("KeyFrame");

To set a KeyFrame on a Timeline, obtain the List with getKeyFrames and add it with the add method.

Now let’s create a sample animation using Timeline. The following rewrites the createShape method.

// import javafx.animation.*;
// import javafx.util.Duration;
 
public void createShape(Pane root){
    Rectangle r = new Rectangle(20, 20, 100, 50);
    r.setFill(Color.CYAN);
    root.getChildren().add(r);
     
    Timeline tl = new Timeline();
    tl.setAutoReverse(true);
    tl.setCycleCount(10);
 
    // create KeyFrames for width
    KeyFrame key_a1 = new KeyFrame(
        new Duration(0),
        new KeyValue(r.widthProperty(),100));
    KeyFrame key_a2 = new KeyFrame(
        new Duration(2500),
        new KeyValue(r.widthProperty(),200));
 
    // create KeyFrames for fill color
    KeyFrame key_b1 = new KeyFrame(
        new Duration(0),
        new KeyValue(r.fillProperty(),Color.rgb(255, 0, 0)));
    KeyFrame key_b2 = new KeyFrame(
        new Duration(2500),
        new KeyValue(r.fillProperty(),Color.rgb(0, 0, 255)));
    tl.getKeyFrames().add(key_a1);
    tl.getKeyFrames().add(key_a2);
    tl.getKeyFrames().add(key_b1);
    tl.getKeyFrames().add(key_b2);
    tl.play();
}

When you run this, the rectangle color changes between red and blue while its width grows and shrinks.

Here, the widthProperty method is used to obtain the width property of Rectangle. This returns a DoubleProperty for a double value.

The fillProperty method is also used to obtain the fill color. This is a Property whose value is a Color. The argument uses the rgb method of the Color class to set a color by specifying RGB brightness values.

Once you can handle Timeline, you can freely manipulate and animate the values of many properties. It is worth looking into what controllable properties Node provides.