4

I have a simple app in Kotlin that draws a rectangle and then uses a fixedRateTimer to update the location of the rectangle 30 times a second. The problem I have is that when I close the window displaying the rectangle the application keeps running and I have to press the red square inside Intellij to actually stop it.

I have tried cancelling the fixedRateTimer before I close the window but the application is still running it just doesn't seem to do anything. If I run the application without the fixedRateTimer it just displays the square and then when I close the window it stops the application.

import javafx.scene.paint.Color
import tornadofx.*
import kotlin.concurrent.fixedRateTimer

class MyApp: App(MyView::class)

class MyView : View() {

    override val root = stackpane {
        group {
            rectangle {
                fill = Color.LIGHTGRAY
                width = 600.0
                height = 480.0
            }

            val myRect = rectangle {
                fill = Color.BLUEVIOLET
                width = 30.0
                height = 30.0
                x = 100.0
                y = 100.0
            }

            fixedRateTimer("default", false, 0L, 1000/30) {
                myRect.x += 1
                if(myRect.x > 200) this.cancel()
            }
        }
    }
}
Jen
  • 43
  • 1
  • 4

1 Answers1

4

You are cancelling your TimerTask, but not the timer. Either pass daemon = true to make a daemon thread, or make sure you save the Timer instance returned from the fixedRateTimer() call, and at some point call cancel on it to stop the non-daemon thread from running the timer before you exit.

The JVM will exit when there are daemon threads running, but not when there are non-daemon threads.

Edvin Syse
  • 7,267
  • 18
  • 24