Java Reference
In-Depth Information
object HelloScalaFX extends JFXApp {
stage = new PrimaryStage {
scene = new Scene {
content = new Label {
text = "Hello ScalaFX"
}
}
}
}
You probably noticed some obvious differences from Java code. In Scala, semicolons are almost always optional
where a line break would otherwise indicate that a statement has ended. This is why there is no semicolon on the
import statements or the assignment to text. Also, Scala has both classes and objects, either or both of which can be
defined in a given file. In this case we are creating an object that subclasses scalafx.application.JFXApp , which
serves as a way of both defining our application and launching it in one step.
Creating an Object that extends scalafx.application.JFXApp is the fundamental pattern for building JavaFX
applications using ScalaFX. This base class has all the core functionality to instantiate a JavaFX application, freeing
you from the usual boilerplate required. All you have to do is take care of whatever initialization you need and
override the stage variable with your own ScalaFX stage object.
This same pattern is followed for the PrimaryStage , Scene , and Label , all of which are ScalaFX objects that have
properties on them for each of the available JavaFX properties of the same class. If you notice from the imports, we
are not actually referring to JavaFX classes, but instead working with proxy classes in a parallel set of ScalaFX classes.
These proxies are interchangeable with the equivalent JavaFX classes using a feature in Scala called implicits, but have
additional functionality that supports this nested object-literal-like syntax.
To run this application, right-click the file and choose Run As Scala Application. On execution, this application
opens a window with the words Hello ScalaFX as shown in Figure 13-13 .
Figure 13-13. Hello ScalaFX application launched from Eclipse
Congratulations! You have successfully run your first ScalaFX application. We now dig more into the design and
features of ScalaFX, showing you how you can build more complex JavaFX applications in Scala.
ScalaFX Proxies and Implicit Conversions
For almost every JavaFX API class, there is an equivalent ScalaFX proxy class. The ScalaFX proxy classes are in a
parallel package structure where javafx is replaced by scalafx and provides additional functionality on top of the
JavaFX APIs. The proxy classes each include one or more of the following.
Delegate object : Each proxy contains a reference back to the JavaFX class that it extends
and wraps.
Property aliases : For all properties, rather than referring to them as fooProperty, you can
instead directly access them as foo.
Property assignment : To support an object-literal-like syntax, the assignment operator is
overloaded to allow you to set writeable properties directly.
 
Search WWH ::




Custom Search