Alan Guo Alan Guo - 1 month ago 28
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);
timeline.getKeyFrames().add(kf);

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

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

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 timeline.play() when you want to reuse the animation.

Good luck!