Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Thursday, September 15, 2016

A Hello, World Kotlin JavaFX App

This is a JavaFX Stage displaying a Label using Kotlin.


This displays a Label containing "Hello, World!" in a new window.

class HelloWorldFXApp : Application() {

    override fun start(primaryStage: Stage?) {

        val vbox = VBox()
        val label = Label("Hello, World!")
        
        vbox.children.add( label )

        val scene = Scene( vbox )

        primaryStage!!.scene = scene
        primaryStage.show()

    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            launch(HelloWorldFXApp::class.java)
        }
    }
}

The main entry point for the application is the @JvmStatic-annotated main function.

The Application subclass HelloWorldFXApp overrides the start method.

The Stage argument may come in as null, so it has a question mark appended to the end of the type.  Later in the method, I access the scene property but first have to tell Kotlin that Stage is not in fact nullable -- non-null is guaranteed -- otherwise, throw an exception.  (There's no point in running if I can't show my message.)

I can use the !! a second time for the show() method, but it appears that this isn't needed as both the IDE and the runtime let me skip the token for that call.

1 comment: