JavaFX

JavaFX Animation Example

Photo of Prasad SayaPrasad SayaApril 29th, 2015Last Updated: April 24th, 2019
0 430 5 minutes read

TheAnimation class provides the core functionality of all animations used in the JavaFX. This abstract class is defined injavafx.animation package.

1. Overview

The following are the main properties ofAnimation:

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

The methodsplay() orplayFromStart() are used to play anAnimation. An animation can be paused by callingpause(), and the nextplay() call will resume the animation from where it was paused.

Animation has two direct subclasses:Transition andTimeline. These two classes are defined in thejavax.animation package.

1.1. Transition

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

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

These are all defined in thejavafx.animation package.

1.2. Timeline

ATimeline can be used to define a free form animation of anyWritableValue, e.g. all JavaFX Properties (defined asProperty interface). ATimeline, defined by one or more Key Frames, processes individualKeyFrame sequentially, in the order specified byKeyFrame.time. The animated properties are defined as key values inKeyFrame.values.

1.3. Examples

This article has examples showingTransition and theTimeline class usage.

TheTransition example demonstrates the usage ofFillTransition,PathTransition andParallelTransition (this usesFadeTransition andRotateTransition).

2. Transition Animation Example

This example shows the usage ofTransition 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();

TheFillTransition creates an animation, that changes the filling of aShape over aDuration. This is done by updating the fill variable of the shape at regular intervals. The shape used is aCircle. This is filled withColor red initially and transitions to yellow. The duration of the transition is set as 3000 millis.

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

TheAnimation‘ssetCycleCount() method defines four cycles and thesetAutoReverse() 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();

ThePathTransition creates a path animation that spans itsDuration. The translation along thePath is done by updating thetranslateX andtranslateY variables of theNode, 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 aShape.

In the example, the shape used is aCircle and thePath a horizontal line. ThePathTransition 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
Want to master JavaFX ?
Subscribe to our newsletter and download theJavaFXProgramming Cookbookright now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

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 ofAnimations in parallel. The example usesFadeTransition andRotateTransition. These are applied to aRectangleShape withColor blue which is the targetNode.

FadeTransition creates a fade effect animation that spans itsDuration. 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 theFadeTransition methodssetFromValue() andsetToValue() 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 theRotateTransition‘ssetByAngle() method. In the above code, the transition is created using the duration and the by angle values.

TheParallelTransition 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 simpleTimeline. 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.

TheKeyFrame,KeyValue andDuration are the main API used inTimeline‘s construction.

TimelineAnimation
TimelineAnimation

4. Download Java Source Code

This was an example ofjavafx.animation.Animation

Download
You can download the full source code of this example here:AnimationExamples.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Prasad SayaPrasad SayaApril 29th, 2015Last Updated: April 24th, 2019
0 430 5 minutes read
Photo of Prasad Saya

Prasad Saya

Prasad Saya is a software engineer with over ten years’ experience in application development, maintenance, testing andconsulting 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.

Related Articles

The JavaFX Print API

July 8th, 2016

JavaFX WebView Example

October 13th, 2016

JavaFX Canvas Example

May 18th, 2016

JavaFX CSS Tutorial

May 5th, 2016

The JavaFX Media API

August 8th, 2016
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.