javafx Animation Animating a property with timeline

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Button button = new Button("I'm here...");

Timeline t = new Timeline(
        new KeyFrame(Duration.seconds(0), new KeyValue(button.translateXProperty(), 0)),
        new KeyFrame(Duration.seconds(2), new KeyValue(button.translateXProperty(), 80))
);
t.setAutoReverse(true);
t.setCycleCount(Timeline.INDEFINITE);
t.play();

The most basic and flexible way to use animation in JavaFX is with the Timeline class. A timeline works by using KeyFrames as known points in the animation. In this case it knows that at the start (0 seconds) that the translateXProperty needs to be zero, and at the end (2 seconds) that the property needs to be 80. You can also do other things like set the animation to reverse, and how many times it should run.

Timelines can animate multiple property's at the same time:

Timeline t = new Timeline(
        new KeyFrame(Duration.seconds(0), new KeyValue(button.translateXProperty(), 0)),
        new KeyFrame(Duration.seconds(1), new KeyValue(button.translateYProperty(), 10)),
        new KeyFrame(Duration.seconds(2), new KeyValue(button.translateXProperty(), 80)),
        new KeyFrame(Duration.seconds(3), new KeyValue(button.translateYProperty(), 90))
);                                                                //   ^ notice X vs Y

This animation will take the Y property from 0 (starting value of the property) to 10 one second in, and it ends at 90 at three seconds. Note that when the animation starts over that Y goes back to zero, even though it isn't the first value in the timeline.



Got any javafx Question?