Java Reference
In-Depth Information
The other part of the JavaFX property pattern that is even more tedious is the creation of new properties. To
define a new property on your class in the same way that the JavaFX APIs define properties, you need a total of one
field and three methods per property. The standard boilerplate for creating a name property on a Person object is
shown in Listing 13-5.
Listing 13-5. JavaFX Property Pattern to Create New Properties in Java
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
public class Person {
private StringProperty name;
public final void setName(String val) { nameProperty().set(val); }
public final String getName() { return nameProperty().get(); }
public StringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(this, "name");
}
return name;
}
}
the preceding code can be further optimized by checking whether the property has been created in the
getName method, and returning null if it has not been created (and thus not initializing the name property).
Note
Although this code is only a bit more verbose than the standard Java property bean pattern, multiply it by the
number of properties you need to define in your application, and you have quite a bit of code to maintain and debug
when there is something that is not working as expected.
GroovyFX has a very elegant solution to this using a compiler hook for AST transformations. Rather than copying
and pasting the property boilerplate each time you want to define a new property, you can simply annotate a variable
with the @FXBindable annotation, and GroovyFX will take care of the rest. It generates exactly the same optimized
code you would write by hand, but does it behind the scenes during the compile phase so that your source code is not
cluttered with the additional logic.
Listing 13-6 shows what the name property would look like in Groovy.
Listing 13-6. GroovyFX Property Pattern to Create New Properties in Groovy
import groovyx.javafx.beans.FXBindable
class Person {
@FXBindable String name
}
The GroovyFX @FXBindable annotation also supports handling the case where a property has a default
initialization value:
class Person {
@FXBindable String name = "Guillaume Laforge"
}
 
 
Search WWH ::




Custom Search