Java Reference
In-Depth Information
List access : All JavaFX ObservableList s are wrapped with a property to access the list that lets
you treat it as a Scala collection.
API enhancements : Some of the JavaFX APIs were not designed with the Scala language and
object-literal construction in mind, so the API authors have taken some liberties in adding
strategic enhancements.
For most uses, you can actually ignore the fact that there is a parallel set of classes, because the Scala implicits
feature allows you to use them interchangeably. Anywhere you have an API that expects a JavaFX class, you can pass
in the ScalaFX proxy and it will automatically get converted back to the JavaFX version. Similarly, if you have an API
that expects the ScalaFX version, there is a Scala implicit conversion that will automatically wrap the JavaFX class in a
ScalaFX proxy.
For example, you can change the Hello ScalaFX code to use a JavaFX label directly and the code will compile and
run fine. The modified version is shown in Listing 13-11.
Listing 13-11. Hello ScalaFX Application to Test Your Newly Created Project
import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.application.JFXApp.PrimaryStage
import scalafx.scene.Scene
import javafx.scene.control.Label
object HelloScalaFXImplicits extends JFXApp {
stage = new PrimaryStage {
scene = new Scene {
content = new Label("Hello ScalaFX Implicits")
}
}
}
Notice that we have changed the import to the normal JavaFX one and used the standard constructor with a
String argument. Even though the Scene content is defined as a collection of ScalaFX Node s, the Scala implicit kicks
in and automatically converts the JavaFX object to a ScalaFX proxy.
The ScalaFX implicit conversions require that you import scalafx.Includes._ , which has been the first line in
all the programs we have shown. This is a special syntax for Scala that is equivalent to a static import in Java, and will
automatically include several utility methods and all the JavaFX to ScalaFX implicit conversions. For the purposes of
ScalaFX development, you should simply treat it as a preamble and include it on all your ScalaFX source files.
JavaFX Properties in Scala
Although we have been using ScalaFX properties directly, we have not directly shown how they work. In particular,
notice the absence of the usual getter/setter pattern found in JavaFX. This is possible because ScalaFX lets us override
the behavior of operators and assignment to substitute more efficient versions of the same operations. To understand
this, let's take a look at the JavaFX property pattern again.
When creating properties for JavaFX in Java, each property definition consists of one variable and three different
accessor methods as shown again in Listing 13-12.
 
Search WWH ::




Custom Search