Search code examples
kotlintornadofx

How can I perform clean up actions upon closing a view in Kotlin/TornadoFX?


I have been searching the docs and IDE autocomplete suggestions and cannot figure this out. The closest I have found is onDelete(), and it is not working the way I envision.

I just need a way to run some clean up code when a view is closed.

Here is a failed attempt using the simple example from the docs.

import tornadofx.*

class MyApp: App(MyView::class)

class MyView: View() {
    // this does not print when the window is closed
    override fun onDelete() {
        super.onDelete()
        println("Print on close!")
    }
    override val root = vbox {
        button("Press me")
        label("Waiting")
    }
}

fun main(args: Array<String>) {
    launch<MyApp>(args)
}

Another failed attempt per a suggestion below:

import tornadofx.*

class MyApp: App(MyView::class)

class MyView: View() {
    // "Closing" is never printed when closing this view"
    override fun onDock() {
        currentWindow?.onHidingProperty()?.onChangeOnce {
            println("Closing")
        }
    }
    override val root = vbox {
        button("Press me")
        label("Waiting")
    }
}

fun main(args: Array<String>) {
    launch<MyApp>(args)
}

Solution

  • I'm using this in my project right now. setOnCloseRequest is my go to!

    override fun onDock() {
        currentWindow?.setOnCloseRequest {
            println("Closing")
        }
    }