JavaFx timeline - set initial delay

I recently started using JavaFx 2.0 , and maybe my problem is very simple, but currently I have no idea how to solve it. For example, let's say I have this little demo application called Clock:

 import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.HBoxBuilder; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.util.Duration; import java.util.Date; public class ClockDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { final Label label = new Label(new Date().toString()); label.setFont(new Font("Arial", 18)); final Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { label.setText(new Date().toString()); } })); timeline.setCycleCount(Timeline.INDEFINITE); Button button = new Button("Start"); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { timeline.play(); } }); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent windowEvent) { timeline.stop(); } }); HBox hBox = HBoxBuilder.create() .spacing(5.0) .padding(new Insets(5, 5, 5, 5)) .children(label, button) .build(); Scene scene = new Scene(hBox, 330, 30); stage.setScene(scene); stage.setTitle("Clock demo"); stage.show(); } } 

Basically, if you press the start button, Timeline will update the time in Label every 5 seconds. But the problem that I am facing is that when I click on the "Start" button, I have to wait 5 seconds until Timeline starts working and updates the time in Label . So, is there a way to eliminate this initial delay time? Thanks in advance.

+4
source share
2 answers

I had the same problem and solved it by adding a KeyFrame with Duration.ZERO at the beginning of the timeline and adding my action to it, and the second KeyFrame is responsible for the delay.

 final Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { label.setText(new Date().toString()); } }) , new KeyFrame(Duration.seconds(5))); 
+8
source

You can forward the timeline by going to simple (1 ms, if accuracy is not so important) before the corresponding key frame:

 timeline.playFrom(Duration.millis(4999)); 
0
source

Source: https://habr.com/ru/post/1497705/


All Articles