Search code examples
javajavafxdelay

Making listener wait javafx


I checked some questions here but I couldn't find a proper answer. Maybe I am using wrong keywords to search. But what I found didn't help. So here is my question. I have some circles and line that are sliding in a certain way. What I want is to update balance variable after the animations perform.

DoubleProperty balance = new SimpleDoubleProperty();

And I update the balance as follows:

if (shapeADone == false) {
    intersecting = arc.centerXProperty().lessThan(boldLine.getEndX() - 13);
    intersecting.addListener((obs, wasIntersecting, isNowIntersecting) -> {
        System.out.println("Collision!");
        animation1.stop();
        animation2.stop();
        animation3.stop();
    });
    again = true;
    balance.setValue(-1);
} else {
    fadeB();
    balance.setValue(1);
}

But in main method I want to do something like this

level1.balance.addListener(ov -> {
           System.out.println("The new value is " +
                   level1.balance.doubleValue());
           if (level1.balance.getValue()==1) {
              //delay setting scene
               primaryStage.setScene(scene2);
           }
       });

I have some animations to perform before setting scene2 but since balance instantly updating, my animations can't be performed. I want to know if there is a way to delay listening balance or setting scene. I tried Thread.sleep and balance.wait but it gives runtime errors.

Edit: This question clearly shows that I was lack of knowlodge about javafx. What I want to do is simple and solution is even more simple. When animation perform to the end I update the value of balance. All I wanted was make sure that animation is showed to the end.


Solution

  • Here is the answer :

    else{
                    animation3.setOnFinished(event -> balance.setValue(1));
                    fadeB();
                }
    

    As Sedrick's comment I change the code like this. Adding setOnFinish to animations which need to be performed solve the problem. It's working.