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 KeyFrame
s 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.