By Alvin Alexander. Last updated: June 13 2018
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
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
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.