Continue your JavaFX Components learning via this tutorial.

Example 1: Animation

Here are the code:

Step 1: Create Project

  1. Open your favorite Java IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Our code will comprise the following java files:

  • AnimationExample.java
  1. In your editor or IDE, create a file known as AnimationExample.java.
  2. Then add the following code:

(a). AnimationExample.java

Go ahead and add the following imports:

import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

We will need to extend our class using the extend keyword. By doing that our class can make use of inheritance to derive properties and functions defined in the parent class.

public class AnimationExample extends Application {

Our class will have the following methods:

  • void main(String[] args)
  • void start(Stage primaryStage)

First of all we will need a main method. This is the entry point of our Java application.

    public static void main(String[] args) {

Here is the full code:

package com.jenkov.javafx.animation;

import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * A simple JavaFX animation examples. Animates a Circle's X property by translating (moving) it 200 points
 * over 10 seconds.
 */

public class AnimationExample extends Application {

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

    public void start(Stage primaryStage) {

        Circle circle = new Circle(50, 150, 50, Color.RED);

        // change circle.translateXProperty from it's current value to 200
        KeyValue keyValue = new KeyValue(circle.translateXProperty(), 200);

        // over the course of 5 seconds
        KeyFrame keyFrame = new KeyFrame(Duration.seconds(10), keyValue);
        Timeline timeline = new Timeline(keyFrame);

        Scene scene = new Scene(new Pane(circle), 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();

        timeline.play();
    }
}

Download

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License