Search code examples
javamultithreadingjavafxtimeline

TimeLINE javaFX thread


At the moment I have a list with images which get displayed for a certain amount of time with a timeline. However I want that a counter is set for each picture i.e. if the amount of time is 30 sec for each picture, there should be a countdown running and showing underneath the picture? Is there a way to achieve that behavior?

        Image i1 = new Image(getClass().getResourceAsStream("IMG_YOGA/01.png"),200,200,false,false);
        Image i2 = new Image(getClass().getResourceAsStream("IMG_YOGA/02.png"),200,200,false,false);
        Image i3 = new Image(getClass().getResourceAsStream("IMG_YOGA/03.png"),200,200,false,false);
        Image i4 = new Image(getClass().getResourceAsStream("IMG_YOGA/04.png"),200,200,false,false);
        Image i5 = new Image(getClass().getResourceAsStream("IMG_YOGA/05.png"),200,200,false,false);
        Image i6 = new Image(getClass().getResourceAsStream("IMG_YOGA/06.png"),200,200,false,false);
        Image i7 = new Image(getClass().getResourceAsStream("IMG_YOGA/07.png"),200,200,false,false);
        Image i8 = new Image(getClass().getResourceAsStream("IMG_YOGA/08.png"),200,200,false,false);

        Y_ImgView.setFitWidth(250);
        Y_ImgView.setFitHeight(300);
        
        final int NUM_FRAMES = 9;
        final int PAUSE_BETWEEN_FRAMES = 30;


        Timeline timeline = new Timeline();
        List<Image> images = List.of(i1,i2,i3,i4,i5,i6,i7,i8,i1);

        for (int i = 0; i < NUM_FRAMES; i++) {
            timeline.getKeyFrames().add(
                new KeyFrame(
                    javafx.util.Duration.seconds(i * PAUSE_BETWEEN_FRAMES), 
                    new KeyValue(Y_ImgView.imageProperty(), images.get(i))
                )
            );
        }

        timeline.setCycleCount(1);
        timeline.play();
        }

Solution

  • Try something like

    IntegerProperty countdown = new SimpleIntegerProperty();
    Label countdownLabel = new Label();
    countdownLabel.textProperty().bind(countdown.asString());
    
    // add label to layout
    

    and then

        Timeline timeline = new Timeline();
        List<Image> images = List.of(i1,i2,i3,i4,i5,i6,i7,i8,i1);
    
        for (int i = 0; i < NUM_FRAMES; i++) {
            timeline.getKeyFrames().add(
                new KeyFrame(
                    javafx.util.Duration.seconds(i * PAUSE_BETWEEN_FRAMES), 
                    new KeyValue(Y_ImgView.imageProperty(), images.get(i)),
                    new KeyValue(countdown, 0),
                    new KeyValue(countdown, PAUSE_BETWEEN_FRAMES)
                )
            );
        }