Search code examples
javafxdurationtimelinekeyframepause

Timeline pause in a process


I wanna add dots to label every 0,5 seconds, but when there are three dots pause the process for 3 second, then remove the dots and start it again (3 times). I tried using this way, but it just add, not pause and not remove :

    Label calling = new Label("Calling");
    Timeline timer = new Timeline();
    KeyFrame first = new KeyFrame(
            Duration.millis(500),
            a -> {
                calling.setText(calling.getText()+".");
                if(calling.getText().endsWith("...")){
                    new Timeline(new KeyFrame(Duration.seconds(3), b-> calling.setText("Calling"))).play();
                }
            }
    );


    timer.getKeyFrames().addAll(first);
    timer.setCycleCount(9);     
    timer.play();
    });

Solution

  • You can do

    import javafx.animation.Animation;
    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.Label;
    import javafx.scene.layout.HBox;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class AddDotsToLabel extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            Label label = new Label("Calling");
    
            EventHandler<ActionEvent> eventHandler = e -> label.setText(label.getText()+".");
            Timeline timeline = new Timeline(
                    new KeyFrame(Duration.millis(500), eventHandler),
                    new KeyFrame(Duration.millis(1000), eventHandler),
                    new KeyFrame(Duration.millis(1500), eventHandler),
                    new KeyFrame(Duration.millis(2000), e -> label.setText("Calling")),
                    new KeyFrame(Duration.millis(5000))
            );
            timeline.setCycleCount(3);
            timeline.play();
    
            label.setPadding(new Insets(20));
            primaryStage.setScene(new Scene(new HBox(label), 120, 40));
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }