A sample Scala/JavaFX application

As a brief note to self, here’s an example JavaFX application written in Scala:

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

class MainWindow extends Application  {
    override def start(stage: Stage) {
        val borderPane = new MainBorderPane
        val scene = new Scene(borderPane, 600, 400)
        scene.getStylesheets.add(getClass.getResource("pizza.css").toExternalForm)
        stage.setScene(scene)
        stage.setTitle("Al’s Pizza")
        stage.show
    }
}

A few redeeming features of this example:

  • It shows the magic recipe to launch a JavaFX application in Scala
  • It shows how to add a stylesheet to a JavaFX Scene in Scala

Scala, JavaFX, and SBT

Note that when you’re working with Scala and JavaFX in SBT (formerly known as the Simple Build Tool), you’ll want to add this setting to your build.sbt file:

fork in run := true

As Monk would say, you’ll thank me later. :)

Other Scala/JavaFX code snippets

While I’m in the neighborhood, here are a couple of other Scala/JavaFX source code snippets.

Scala + JavaFX Button (handling a button action)

val placeOrderButton = new Button

placeOrderButton.setText("Start An Order")
placeOrderButton.setOnAction((e: ActionEvent) => {
    println("Hello World!")
})

placeOrderButton.setFont(new Font("Arial", 24))

Spacer

val spacer = new Region
spacer.setPrefHeight(40)

TextField

val searchField = new TextField
searchField.setPromptText("<search>")

VBox

val vbox = new VBox
vbox.setSpacing(40)
vbox.setAlignment(Pos.CENTER)
vbox.getChildren.addAll(alsPizzaLabel, placeOrderButton, spacer)

MenuItem

Some code to work with a MenuItem, Alert, Buttons, and ButtonType:

addNoteMenuItem.setOnAction(e => {
    val alert = new Alert(AlertType.CONFIRMATION)
    val okButton = new ButtonType("OK")
    val cancelButton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE)

    alert.setTitle("Add Note")
    val editNotePane = new EditNotePane
    alert.getDialogPane().setExpandableContent(editNotePane)
    alert.showAndWait()
})

Summary

If you’re starting to work with Scala and JavaFX, I hope those code samples are helpful.