A Scala version of the JavaFX “Hello, world” example

If you’re interested in seeing a Scala 2 version of Oracle’s JavaFX “Hello, world” application, here you go:

package hello
 
import javafx.application.Application
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.layout.StackPane
import javafx.stage.Stage

object HelloWorld
{
    def main(args: Array[String])
    {
        Application.launch(classOf[HelloWorld], args: _*)
    }
}

class HelloWorld extends Application
{
    override def start(primaryStage: Stage)
    {
        primaryStage.setTitle("Hello World!")
        val btn = new Button
        btn.setText("Say 'Hello World'")
        btn.setOnAction((e: ActionEvent) => {
            println("Hello World!")
        })
        
        val root = new StackPane
        root.getChildren.add(btn)
        primaryStage.setScene(new Scene(root, 300, 250))
        primaryStage.show
    }

}

All I did was to convert their Java version of the “Hello, world” JavaFX program to Scala. That sounds easy, but there was a little trick in getting that main method working properly. Feeling lazy, I didn’t try to figure it out, and just Google’d until I found this solution on SO.

I don’t know if I’ll keep going down this road or not, but if I do, I may use the ScalaFX project instead of using Scala with JavaFX. It looks pretty cool, though at the moment I don’t know how well supported it is.