new Thread, application still running after Stage-close

前端 未结 2 494
梦毁少年i
梦毁少年i 2021-01-15 01:41

So I followed this tutorial: https://www.youtube.com/watch?v=gyyj57O0FVI

and I made exactly the same code in javafx8.

public class CountdownControll         


        
2条回答
  •  星月不相逢
    2021-01-15 02:13

    Part I

    A thread, when created, runs independent of other threads. You have a new thread which has an infinite loop, which implies, it will keep running forever, even after the stage has been closed.

    Normally, using a infinite loop is not advised, because breaking out of it is very difficult.

    You are advised to use :

    • TimerTask
    • ScheduledExecutorService

    You can then call either one of them (based on whatever you are using)

    • TimerTask.cancel()
    • ScheduledExecutorService.shutdownNow()

    when your stage is closed. You can use something like :

    stage.setOnCloseRequest(closeEvent -> {
           timertask.cancel();  
    });  
    

    JavaFX API's (thanks to James_D comment's)

    These do not need to be explicitly canceled as ScheduledService uses daemon threads and AnimationTimer runs on the JavaFX thread.

    • ScheduledService
    • AnimationTimer

    Part II

    Your second part of the question has been answered time and again in the forum.

    You need to be on the JavaFX Application thread to use scene graph elements.

    Since you have created a new thread and trying to update label, which is a JavaFX node, it throws the exception. For more information, please visit:

    JavaFX error when trying to remove shape

    Why am I getting java.lang.IllegalStateException "Not on FX application thread" on JavaFX?

    Javafx Not on fx application thread when using timer

提交回复
热议问题