You can set interpolators when creating KeyValue:
new KeyValue(node.translateYProperty(), 200, Interpolator.LINEAR);
The default interpolator is Interpolator.LINEAR.
Visually, it looks like an abrupt stop at the end of the animation. To soften that, you can use one of the easing interpolators:
- Interpolator.EASE_IN: Starts slowly
- Interpolator.EASE_OUT: Ends slowly
- Interpolator.EASE_BOTH: Starts and ends slowly
You can see them all at work simultaneously by running the following code:
// chapter5/basics/InterpolatorsDemo.java
public void start(Stage primaryStage) {
VBox root = new VBox(10);
Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
Stream.of(
Interpolator.LINEAR,
Interpolator.EASE_IN,
Interpolator.EASE_BOTH,
Interpolator.EASE_OUT
).forEach((interpolator)-> {
Circle node = new Circle(30, Color.RED);
root.getChildren().add(node);
KeyFrame keyFrame = new KeyFrame(Duration.seconds(2),
new KeyValue(node.translateXProperty(), 240, interpolator));
timeline.getKeyFrames().add(keyFrame);
});
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
timeline.play();
}
Here are several screenshots of this app running:
Note that all circles touch the right wall simultaneously—interpolators are responsible only for the calculation of the intermediate states of the properties; starting and ending values are set by KeyValue objects.
The last predefined interpolator is Interpolator.DISCRETE. It's very simple and doesn't calculate anything in between—it just instantly changes the value of the property once Duration has passed.