Java Reference
In-Depth Information
each Property object may have at most one active unidirectional binding at a time. it may have as many
bidirectional bindings as you want. the isBound() method pertains only to unidirectional bindings. Calling bind() a
second time with a different ObservableValue argument while a unidirectional binding is already in effect will unbind the
existing one and replace it with the new one.
Caution
Understanding the Binding Interface
The Binding interface defines four methods that reveal the intentions of the interface. A Binding object is an
ObservableValue whose validity can be queried with the isValid() method and set with the invalidate() method.
It has a list of dependencies that can be obtained with the getDependencies() method. And finally a dispose()
method signals that the binding will not be used anymore and resources used by it can be cleaned up.
From this brief description of the Binding interface, we can infer that it represents a unidirectional binding
with multiple dependencies . Each dependency, we imagine, could be an ObservableValue to which the Binding is
registered to receive invalidation events. When the get() or getValue() method is called, if the binding is invalidated,
its value is recalculated.
The JavaFX properties and bindings framework does not provide any concrete classes that implement the
Binding interface. However, it provides multiple ways to create your own Binding objects easily: You can extend the
abstract base classes in the framework; you can use a set of static methods in the utility class Bindings to create new
bindings out of existing regular Java values (i.e., unobservable values), properties, and bindings; you can also use a set
of methods that are provided in the various properties and bindings classes and form a fluent interface API to create
new bindings. We go through the utility methods and the fluent interface API in the “Creating Bindings” section later
in this chapter. For now, we show you the first example of a binding by extending the DoubleBinding abstract class.
The program in Listing 4-3 uses a binding to calculate the area of a rectangle.
Listing 4-3. RectangleAreaExample.java
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
public class RectangleAreaExample {
public static void main(String[] args) {
System.out.println("Constructing x with initial value of 2.0.");
final DoubleProperty x = new SimpleDoubleProperty(null, "x", 2.0);
System.out.println("Constructing y with initial value of 3.0.");
final DoubleProperty y = new SimpleDoubleProperty(null, "y", 3.0);
System.out.println("Creating binding area with dependencies x and y.");
DoubleBinding area = new DoubleBinding() {
private double value;
{
super.bind(x, y);
}
@Override
protected double computeValue() {
System.out.println("computeValue() is called.");
return x.get() * y.get();
}
};
 
 
Search WWH ::




Custom Search