简体   繁体   English

等待PathTransition完成,直到从JavaFX中的函数返回

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

I'm trying to implement a program like this using JavaFX: 我正在尝试使用JavaFX实现这样的程序:

We have a number of objects of Type Foo on the scene (which are shown by circles). 场景中我们有许多类型为Foo的对象(由圆圈显示)。
Each one of them has a method called move() which would move the object to another location on the scene. 它们每个都有一个名为move()的方法,该方法会将对象移动到场景中的另一个位置。 Then it finds another object (by calling another method) and calls the move method on the found object. 然后,它找到另一个对象(通过调用另一个方法),并在找到的对象上调用move方法。 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. 我希望圆的运动对用户可见并且是连续的,但是当我定期使用PathTransition时,所有对象(几乎)同时(几乎)同时移动,因为每个PathTransition都在新线程上并在其play()之后运行,函数将继续并调用findNextFoo()方法。

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. 我尝试使用setOnFinished for PathTransition完成时更改标志,然后使用while(true)等待标志设置为true,然后调用foo.move()方法。 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). Thread.sleep()也无法按我想要的方式工作(所有移动都在延迟后但同时完成)。

Any help would be appreciated, thanks. 任何帮助,将不胜感激,谢谢。

You must not block the application thread like you do if you use while(true) or Thread.sleep . 如果使用while(true)Thread.sleep则不能像您那样阻塞应用程序线程。

You could use SequentialTransition if you're able to determine all transitions in advance. 如果您能够提前确定所有转换,则可以使用SequentialTransition

However using the onFinished event would probably require less modification of the code. 但是,使用onFinished事件可能需要较少的代码修改。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM