Search code examples
javakotlintornadofx

How to close entire app when a TornadoFX window is closed?


How can I close the entire app when a TornadoFX window is closed?

With JavaFX it is usually:

val app = JFrame()
app.defaultCloseOperation = JFrame.EXIT_ON_CLOSE

Is there a way to detect on TornadoFX View closed?


Solution

  • Usually, closing the primary stage activates the App class's stop() function. This is what you want to override to do your own shutdown routine:

    class MyApp : App (FirstView::class) {
        override fun stop() {
            super.stop()
            /* Do your shutdown routine here  */
        }
    }
    

    However, I've had instances where that logic gets broken and only closing all program windows works. If you have a 'main window' that you want to ensure shuts down the program, add this in your App class as well:

    override fun start(stage: Stage) {
       stage.setOnHiding { stop() }
    }
    

    Edit: I would use your IDE to look at what exactly the stop() function does for you, as well as look at the answers linked by Abra to see what the vanilla JavaFX Platform.exit() function does as TornadoFX is just JavaFX at its core, and this is most explicit shutdown of a JavaFX application. Some users in that thread reported that their program would still hang depending on what they were doing and suggested adding System.exit(0);, aka exitProcess(0) in Kotlin, to their shutdown routine to make sure the program dies.