//rich client /
defined in the Observable interface
to add an InvalidationListener to the
DoubleProperty referenced by valueA.
This invalidated() method is invoked
whenever the valueA property is no longer
valid, which means that the value might
have changed. To update the label to the
right of the slider, we’ll put some code in
the invalidated() method that casts the
Observable object to a DoubleProperty,
gets its value, converts it to a string, and
sets the text of labelA to the string.
Go ahead and fill in the lines indicated
by the “TO DO” comments, so the code
in Listing 2 turns into the code shown in
Listing 3.
Note: This use of an InvalidationListener
is for demonstration purposes, showing
that the Observable argument passed
into the invalidated() method can be
read with the getValue() method. The act
of reading the value, however, forces it
to be reevaluated, because the implementation of SimpleDoubleProperty uses
lazy evaluation. This result defeats the
purpose of using an InvalidationListener,
which is to be notified that a value is
no longer valid without forcing it to be
reevaluated. In contrast, the purpose of
the ChangeListener (which you’ll experience next) is to read the value as soon as
it changes.
LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6 LISTING 7
valueA.addListener(new InvalidationListener() {
public void invalidated(Observable observable) {
// observable is a DoubleProperty
// TO DO: Cast the Observable object to a DoubleProperty; get its value
// and convert it to a String, and set the text of
// labelA to the String.
COMMUNITY
}
});
JAVA IN ACTION
Download all listings in this issue as text
Step 2: Adding a ChangeListener to
Detect Changes to the Value Property
of the Middle Slider
To dynamically update the label text as
the middle slider is moved, this time
we’ll add a ChangeListener to the property that tracks with the value of the
middle slider.
As in Step 1, the starter code for the
middle slider in BindingExampleMain.java
instantiates a SimpleDoubleProperty and
bidirectionally binds the value property
of the slider with it, as shown in Listing 4.
Add a ChangeListener that updates
the text property of the label. As
shown in the UML diagram in
ABOUT US
blog
Jim Weaver introduces the concept of binding in
JavaFX 2.0.
Step 3: Using bind(), unbind(), and
Bind Expressions to Manage the Text
Property of the Bottom Label
To dynamically update the label text as
the bottom slider is moved, this time
we’ll bind the text property of the label
to the properties that track with the values of the sliders.
As in Step 2, the starter code for the
bottom slider in BindingExampleMain.java
instantiates a SimpleDoubleProperty and
bidirectionally binds the value property
of the slider with it, as shown in Listing 7.
Add a ChangeListener to the checkbox.
As shown in Figure 3, there is a checkbox
labeled Bind that, when selected, causes
53
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////////// MAY/JUNE 2012