简体   繁体   English

如果A由B启动,如何在JavaFX线程B中改变线程A的场景?

[英]How to make thread A change scene in JavaFX thread B if A was launched by B?

Im trying to make a JavaFX game. 我正在尝试制作JavaFX游戏。 There is a main thread (B) that launches some physical calculations in another thread (A) onMouseReleased. 有一个主线程(B)在onMouseReleased的另一个线程(A)中启动一些物理计算。 Thread A calculates desired movements and makes figures move on the screen. 线程A计算所需的移动并使图形在屏幕上移动。 After the ball has stopped, scene should be changed in order to show results and let user restart level or go further. 停球后,应更改场景以显示结果,并让用户重新启动级别或走得更远。

If join() is used in B to wait for finish of A and then update the scene, B doesnt respond while calculations in A are performed and does not show movement of figures. 如果在B中使用join()等待A完成,然后更新场景,则在执行A中的计算时B不会响应,并且不会显示图形的移动。 It is not acceptable. 这是不可接受的。

If an attempt is made to change app scene from A, i get 如果试图从A更改应用场景,我会得到

java.lang.IllegalStateException: Not on FX application thread java.lang.IllegalStateException:不在FX应用程序线程上

What concept should i realize to make after-game screen appear? 使赛后画面出现时我应该意识到什么概念?

Here is the structure of thread A: 这是线程A的结构:

class Physics implements Runnable{
    private Ball ball;
    private Pane game;
    private Thread t;
    private boolean paused;
    Physics(Pane game, Ball ball){
        super();
        this.ball=ball;
        this.game=game;
        this.paused=true;
        t=new Thread(this);
    }
    public void run(){
        this.unPause();
        while(ball.getXSpeed()!=0||ball.getYSpeed()!=0){
            try {
                sleep(20);

            }
            catch (InterruptedException ex){
                ball.stop();
            }
            if(!paused) {
                ball.step();
                interactGravities();
                checkObstacles();
                checkTargets();
                checkEdges();
            }
        }
        Main.showResult();
    }
}

Each of checkObstacles, checkTargets, checkEdges can make the ball.stop(), which makes the while loop end. 每个checkObstacles,checkTargets,checkEdges都可以使ball.stop()结束while循环。 Main.showResult() is the method that tries to setScene() in thread B but gets java.lang.IllegalStateException. Main.showResult()是尝试在线程B中设置setScene()但获取java.lang.IllegalStateException的方法。

You should use Platform.runLater() . 您应该使用Platform.runLater()。 This command force to execute the supplied task from the Runnable( taken in the argument of Platform.runLater method) in the JavaFx thread. 此命令强制从JavaFx线程中的Runnable(在Platform.runLater方法的参数中获取)执行提供的任务。 Use setScene command or others function that manipulate the Scene inside that Runnable. 使用setScene命令或其他可在Runnable内部操作场景的函数。

PS the runnable can be also expressed as a Lambda Expression in java8. PS可运行对象也可以在Java8中表示为Lambda表达式。

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

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