Friday 13 June 2014

Starting up JavaFX in Scala

Scala is great, and JavaFX is a pretty amazing user interface system.  So, I want to combine them.  This is a short note about how to get things going quickly.

A JavaFX start-up class needs to have a main() method just like any other start-up class, and also needs to inherit from Application, so code like this can be written:

class Start extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    public void start(Stage stage) {
        ....
    }
}

The application starts up an instance of the class and passes the main window (the 'Stage') to the start method.

Trying to copy this in Scala results in this:

object Start {
    def main(args: Array[String]) : Unit = {
        Application.launch(args:_*)
    }
}

class Start extends Application {
    override def start(stage: Stage) = {
        ....
    }
}

(args:_* means take the array 'args' and set the elements as individual varargs parameters)

This code won't work.  There are two reasons:  There isn't the connection between the Start object and the Start class in Scala that corresponds to that between static methods and a class in Java.  Secondly, there already is an Application class in the Scala defaults.

We can deal with the first problem by explicitly mentioning the class that the application needs to start up, and the second problem can be fixed by Scala import renaming:

import javafx.application.{Application => FXApplication}

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

class Start {
    override def start(stage: Stage) = {
        ....
    }
}

That does it!

In my next programming post I'll show how to get FXML binding working with Scala.


No comments: