//rich client /
Listing 5 into the Stop WatchModel.java
file. When you’re done, let’s move on to
the next concept, which involves creating a custom binding.
Then, add the following lines to
StopWatchNode.java:
import java.text.SimpleDateFormat;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.IntegerProperty;
Step 3: Create a Custom Binding
As mentioned previously, the
elapsed time value is formatted
as an integer in Figure 6 but as a
minutes:seconds:milliseconds string
in Figure 3. This is accomplished by
using a custom binding instead of
the default binding provided by the
SimpleIntegerProperty.
To implement a custom binding,
our example defines a class named
TimeStringBinding that extends the
StringBinding class, which implements the Binding interface shown in
Figure 1. You can see the code for the
TimeStringBinding class in Listing 6.
As shown in Listing 6, to implement the custom binding we do the
following:
■ ■ Define a constructor with the input
arguments for the binding, calling the
bind() method of the superclass.
■ ■ Override the computeValue() method,
returning the desired output value for
the binding.
To use this custom binding in the
LazyInitEvalExercise project, comment out the following lines in the
Stop WatchNode.java file:
elapsedTimeStrProperty.bind(
new TimeStringBinding(
stopWatchModel.elapsedMillis
Property()
)
);
public class TimeStringBinding extends StringBinding {
private SimpleDateFormat timeFormat = new SimpleDateFormat("mm:ss:SSS");
private IntegerProperty millis;
public TimeStringBinding(IntegerProperty millisArg) {
super.bind(millisArg);
millis = millisArg;
}
JAVA IN ACTION
For extra credit, also replace the
binding for the lapNode textProperty() in
a similar manner so that it appears as
shown in Figure 3.
Go ahead and run the
LazyInitEvalExercise application to verify
that the custom bindings cause the
elapsed time and lap time values to be
formatted as shown in Figure 3.
@Override
protected String computeValue() {
int elapsedInt = millis.get();
return timeFormat.format(elapsedInt);
}
}
Conclusion
JavaFX 2 comes with numerous classes
and interfaces that provide a powerful
properties and bindings framework. You
can optimize the evaluation of bindings
and the initialization of properties by
using the lazy approaches demonstrated
above. In addition, you can define custom bindings when augmenting the
default behavior of the bindings in the
JavaFX 2 API as desired. </article>
ABOUT US
elapsedTimeStrProperty.bind(
stopWatchModel.elapsedMillisProp
erty()
blog
.asString()
);
LEARN MORE
•;“Using JavaFX Properties and Binding”
•;Michael Heinrichs’ blog, which includes
entries on JavaFX properties and bindings