Monday, January 19, 2015

Run JavaFx App under Scala within Eclipse

Writing a JavaFX application with Scala that can be started in Eclipse with the usual "Run as -> Scala Application" is trivial but far from obvious. The key is to create a companion object with a main method that calls Application.launch() with the class of the application and the command line arguments.

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

Here the complete code of a JavaFX example Application:

  
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

class HelloJavaFX extends Application {
  override def start(stage: Stage) {
    stage.setTitle("HelloJavaFX!")
    val btn = new Button
    btn.setText("Press me")
    btn.setOnAction(new EventHandler[ActionEvent] {
      override def handle(e: ActionEvent) {
        println("Hello JavaFX!")
      }
    })

    val root = new StackPane
    root.getChildren.add(btn)
    stage.setScene(new Scene(root, 300, 250))
    stage.show
  }
}

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

Also don't forget that the JavaFX runtime jar jfxrt.jar is required on the class path.