Adding Animation in JavaFX Pie Chart

In this tutorial session, we are going to add animation with JavaFX Pie Chart. We will perform an animation on Pie Chart Slices when we click on any one of these.


Let’s Begin:

Step 1: Please watch Part 1 and Part 2 of this tutorial in which we first learn to create a Pie Chart using FXML and then handle click events on slices. 

Tutorial Part #1: How to create a pie chart In JavaFX

Tutorial Part #2: Handling Events for Pie Chart in JavaFX | Display pie chart values on Mouse Click.

Well, I hope you guys have seen Tutorial parts 1 and 2 of this session, now from here in step 2 we will do some action. Let’s do it.

Step 2: Follow my instructions as described in the below video tutorial and the below-given code explanation for easy understanding:

Steps to apply Animation:
– read the bounds of the pie chart slice
– prepare new X and Y positions for slice

– Calling reset method to reset location
 data.getNode().setTranslateX(0);
data.getNode().setTranslateY(0);

– Using TranslateTransition class for adding animation
TranslateTransition tt = new TranslateTransition(Duration.millis(1500), data.getNode());

– Now set new X and Y positions for a slice with help of TraslateTransition class object.
 tt.setByX(newX);
tt.setByY(newY);

tt.setCycleCount(3); for slice move outside and come back.
tt.play(); to start animation,

Please check this code snippet :
Bounds b1 = data.getNode().getBoundsInLocal();
double newX = (b1.getWidth()) / 2.0 + b1.getMinX();

System.out.println(b1.getMinX());
double newY = (b1.getHeight()) / 2.0 + b1.getMinY();

// Make sure pie wedge location is reset
data.getNode().setTranslateX(0);
data.getNode().setTranslateY(0);

TranslateTransition tt = new TranslateTransition(
Duration.millis(1500), data.getNode());

tt.setByX(newX);
tt.setByY(newY);

tt.setAutoReverse(true);
tt.setCycleCount(2);
tt.play();
 
If you found this tutorial useful and would like to support me, you can do so by buying me a coffee using that button above on the right-hand side!

1 thought on “Adding Animation in JavaFX Pie Chart”

Leave a Comment