Java Reference
In-Depth Information
Although most of the ScalaFX operators are fairly intuitive, there are a few cases where it was not possible to use
the standard operators. These include:
if/else : These are Scala language keywords, so as demonstrated earlier, these have been
replaced with when/otherwise , just as in the corresponding JavaFX APIs.
==/!= : Directly using the equality and inequality operators produces some unwanted
interactions with the same operations on the core Scala object base class. Instead use === and
=!= , both of which were carefully chosen to have the same precedence rules as the operators
they are replacing.
As an added bonus, you can specify the precision of the === and =!= operators for numeric comparison by using
the following syntax.
aboutFiveHundred <== value1 === 500+-.1
This would test that value1 is less than .1 away from 500.
API Enhancements
By this time, you should have a pretty good feel for how the JavaFX applications you have been building translate
to equivalent ScalaFX code. In general the ScalaFX APIs mirror the JavaFX APIs, providing equivalent functionality.
However, in some cases it was actually possible to provide an improved API or alternative choice that matches the
declarative style of programming that ScalaFX encourages. In this section we cover a few different areas in which
ScalaFX improves on the JavaFX APIs.
Closures
One of the features that is new to Java 8 is lambdas or closures. This simplifies the case where you are creating event
listeners or similar callbacks where you need to implement an interface that contains a single method.
Most modern JVM languages have had closures as a core language feature for quite a while, as does the Scala
language. This means that anywhere you would normally have to implement an event or property listener, you can
instead use a closure to simplify your code.
Earlier in the Vanishing Circles application we showed an example of a closure to set a mouse click handler:
onMouseClicked = {
Timeline(at (3 s) {radius -> 0}).play()
}
The closure part is really that simple; all you have to do is surround your method logic with curly braces and
assign it to the property for the event handler. There is another variant of this if you also need access to some of the
variables passed in, such as the MouseEvent :
onMouseClicked = { (e: MouseEvent) =>
Timeline(at (3 s) {radius -> 0}).play()
}
Layout Constraints
The layout constraint mechanism introduced in JavaFX 2 is very flexible, because it lets layout authors define their
own constraints that get stored on Node , but is also not ideal from an application developer standpoint. It forces your
code into an imperative pattern where you add children in one step and then set constraints following that.
 
Search WWH ::




Custom Search