Spekular
Spekular

Reputation: 99

JavaFX repeat loop when transition ends

I'm trying to perform the following loop:

  1. Update some variables
  2. Play a transition based on/representing the variables
  3. Once the transition is done, go to 1

This repeats forever. I made it work with the following:

//Step 3
transition.setOnFinished(new EventHandler<ActionEvent>(){
    @Override
    public void handle(ActionEvent event){
        doTheThing(); //Step 1, updates data
        transition.setToValue(data);
        transition.play(); // Step 2
    }
});

transition.play(); //Triggers first repeat

Of course, this is an endless recursive loop, which isn't a good idea. The problem is, I can't figure out how else to trigger the repeat once the transition finishes. I've tried using a loop:

while (1==1){
    doTheThing();
    transition.setToValue(data);
    transition.play();
}

But not only does this not wait for the transition (to be expected and not a problem for me), it doesn't play the transition at all, and the program is unresponsive. I've also tried this:

transition.setOnFinished(new EventHandler<ActionEvent>(){
    @Override
    public void handle(ActionEvent event){
        ready = true;
    }
});
while (1==1){
    if (ready){
        ready = false;
        doTheThing();
        transition.setToValue();
        transition.play();
    }
}

But it acts the same as solution #2. I would prefer to not have a wait programmed in, but even if I did, I'm not sure how to make the loop wait before it repeats, without also stopping the transition from playing.

What can I do instead?

Upvotes: 4

Views: 4578

Answers (1)

eckig
eckig

Reputation: 11134

I would suggest you to use a TimeLine where you can specify the cycleCount which you can set to INDEFINITE.

Example:

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), ev -> {
    // TODO do something meaningful here
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

Upvotes: 7

Related Questions