javafx timeline
In JavaFX, a Timeline
is a class that represents a series of key frames that define a sequence of changes over time. It is used for creating animations and other time-based effects in JavaFX.
To use a Timeline
in JavaFX, you first create a Timeline
object and specify one or more KeyFrame
objects that define the changes you want to make over time. Each KeyFrame
specifies a time duration and a EventHandler
that is called when that duration has elapsed. You can also specify an interpolation method to use between key frames, which determines how the values are calculated between each key frame.
Here's an example of how to use a Timeline
to create a simple animation that changes the color of a rectangle over time:
import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class TimelineExample extends Application { @Override public void start(Stage primaryStage) { // Create a rectangle Rectangle rectangle = new Rectangle(100, 100, Color.RED); // Create a Timeline with a KeyFrame that changes the color of the rectangle after 2 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(2), event -> { rectangle.setFill(Color.BLUE); })); timeline.setCycleCount(Animation.INDEFINITE); // Create a StackPane layout and add the rectangle to it StackPane layout = new StackPane(rectangle); // Create a Scene with the layout and set it on the stage Scene scene = new Scene(layout, 300, 200); primaryStage.setScene(scene); // Start the timeline timeline.play(); // Show the stage primaryStage.show(); } public static void main(String[] args) { launch(args); } }
In this example, we create a red rectangle and a Timeline
that changes the color of the rectangle to blue after 2 seconds. We set the cycleCount
of the Timeline
to Animation.INDEFINITE
so that it will continue running indefinitely. We create a StackPane
layout and add the rectangle to it. We then create a Scene
with the layout and set it on the stage. Finally, we start the Timeline
by calling the play()
method on it.
You can customize the Timeline
by adding more KeyFrame
objects, adjusting the duration and interpolation method, and specifying what happens when the Timeline
finishes by using the various methods of the Timeline
class.