Karegar
Karegar

Reputation: 21

waiting for a PathTransition to finish until returning from a function in JavaFX

I'm trying to implement a program like this using JavaFX:

We have a number of objects of Type Foo on the scene (which are shown by circles).
Each one of them has a method called move() which would move the object to another location on the scene. Then it finds another object (by calling another method) and calls the move method on the found object. It's something like this:

class Foo {
    Circle circle;
    void move() {
        // change circle location
        // HERE, I WANT TO WAIT UNTIL CIRCLE HAS MOVED ON THE SCENE
        Foo f = findNextFoo();
        foo.move();
    }
}

I want the circles' movements to be visible and sequential to the user, but when I use PathTransition regularly, all of the objects move at (almost) the same time, since each PathTransition is running on a new thread and after its play(), function will continue and calls findNextFoo() method.

I have tried to use setOnFinished for PathTransition to change a flag when it has finished, and then using a while(true) to wait until the flag has been set to true and then called foo.move() method. This also doesn't work and makes my program crash.

Thread.sleep() also doesn't work the way I want (all the movements are done after a delay but at the same time).

Any help would be appreciated, thanks.

Upvotes: 0

Views: 1016

Answers (1)

fabian
fabian

Reputation: 82461

You must not block the application thread like you do if you use while(true) or Thread.sleep.

You could use SequentialTransition if you're able to determine all transitions in advance.

However using the onFinished event would probably require less modification of the code. Simply start the next transition from the event handler instead of using a flag+infinite loop:

void move() {
    PathTransition transition = ...

    transition.setOnFinished(event -> {
        // after transition is finished continue with next one
        Foo f = findNextFoo();
        foo.move();
    });
    transition.play();
}

Upvotes: 1

Related Questions