Java Reference
In-Depth Information
.and(c.add(a).greaterThan(b)))
.then(s.multiply(s.subtract(a))
.multiply(s.subtract(b))
.multiply(s.subtract(c)))
.otherwise(0.0D);
a.set(3);
b.set(4);
c.set(5);
System.out.printf("Given sides a = %1.0f, b = %1.0f, and c = %1.0f," +
" the area of the triangle is %3.2f\n", a.get(), b.get(), c.get(),
Math.sqrt(areaSquared.get()));
a.set(2);
b.set(2);
c.set(2);
System.out.printf("Given sides a = %1.0f, b = %1.0f, and c = %1.0f," +
" the area of the triangle is %3.2f\n", a.get(), b.get(), c.get(),
Math.sqrt(areaSquared.get()));
}
}
Inasmuch as there is no ready-made binding method in DoubleExpression that calculates the square root, we
create a DoubleBinding for areaSquared instead. The constructor argument for When() is a BooleanBinding built out
of the three conditions on a , b , and c . The argument for the then() method is a DoubleBinding that calculates the
square of the area of the triangle. And because the then() argument is numeric, the otherwise() argument also has
to be numeric. We choose to use 0.0D to signal that an invalid triangle is encountered.
instead of using the When() constructor, you can also use the factory method when() in the Bindings utility
class to create the When object.
Note
When we run the program in Listing 4-7, the following output is printed to the console:
Given sides a = 3, b = 4, and c = 5, the area of the triangle is 6.00.
Given sides a = 2, b = 2, and c = 2, the area of the triangle is 1.73.
If the binding defined in Listing 4-7 makes your head spin a little, you are not alone. We choose this example
simply to illustrate the use of the fluent interface API offered by the When class. As a matter of fact, this example might
be better served with a direct subclassing approach we first introduced in the “Understanding the Binding Interface”
section earlier in this chapter.
The program in Listing 4-8 solves the same problem as Listing 4-7 by using the direct extension method.
Listing 4-8. HeronsFormulaDirectExtensionExample.java
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
 
Search WWH ::




Custom Search