Alan Guo Alan Guo - 1 year ago 97
Java Question

How to dynamically play JavaFX animations

I have a Java application where, when I click a button, an ImageView moves a certain amount across the screen. How can I make it so that every time I click the button, an animation is run? I know how to make a click button and have it run a function. I just don't know how to use animations properly to dynamically run new animations.

public Timeline moveAnimation(double x, double y) {
// horizontal movement
KeyValue kv = new KeyValue(turtle.xProperty(), x);
KeyFrame kf = new KeyFrame(Duration.millis(500), kv);

// vertical movement
KeyValue kv2 = new KeyValue(turtle.yProperty(), y);
KeyFrame kf2 = new KeyFrame(Duration.millis(500), kv2);

return timeline;

public void move(double x, double y) {
moveAnimation(x, y).play();

The above method will play once. When I try to run the move() method again with new values, nothing happens.

Answer Source

The Timelineholds all of the animation "steps" (AKA: KeyFrame).

in the move method, you should assign a variable of type Timeline with the returned value from the moveAnimation method, like this:

public void move(double x, double y) {
     Timeline timeline = moveAnimation(x, y).play();
     //use timeline wherever...

And then call when you want to reuse the animation.

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download