简体   繁体   中英

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

Im trying to make a JavaFX game. There is a main thread (B) that launches some physical calculations in another thread (A) onMouseReleased. Thread A calculates desired movements and makes figures move on the screen. 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. It is not acceptable.

If an attempt is made to change app scene from A, i get

java.lang.IllegalStateException: Not on FX application thread

What concept should i realize to make after-game screen appear?

Here is the structure of thread 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. Main.showResult() is the method that tries to setScene() in thread B but gets java.lang.IllegalStateException.

You should use 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. Use setScene command or others function that manipulate the Scene inside that Runnable.

PS the runnable can be also expressed as a Lambda Expression in java8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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