Java Reference
In-Depth Information
to initialize the controller. This method can be used to configure the controller before the
GUI is displayed. Line 65 calls the currency object's setRoundingMode method to specify
how currency values should be rounded. The value RoundingMode.HALF_UP indicates that
values greater than or equal to .5 should round up—for example, 34.567 would be for-
matted as 34.57 and 34.564 would be formatted as 34.56.
61
// called by FXMLLoader to initialize the controller
62
public void initialize()
63
{
64
// 0-4 rounds down, 5-9 rounds up
65
currency.setRoundingMode( RoundingMode.HALF_UP );
66
67
// listener for changes to tipPercentageSlider's value
tipPercentageSlider.valueProperty().addListener(
new ChangeListener<Number>()
{
@Override
public void changed(ObservableValue<? extends Number> ov,
Number oldValue, Number newValue)
{
tipPercentage =
BigDecimal.valueOf(newValue.intValue() / 100.0 );
tipPercentageLabel.setText(percent.format(tipPercentage));
}
}
);
68
69
70
71
72
73
74
75
76
77
78
79
80
81
}
82
}
Fig. 25.21 | TipCalculatorController 's initalize method.
Using an Anonymous Inner Class for Event Handling
Each JavaFX control has various properties, some of which—such as a Slider 's value—
can notify an event listener when they change. For such properties, you must manually
register as the event handler an object of a class that implements the ChangeListener in-
terface from package javafx.beans.value . If such an event handler is not reused, you'd
typically define it as an instance of an anonymous inner class —a class that's declared with-
out a name and typically appears inside a method declaration. Lines 68-80 are one state-
ment that declares the event listener's class, creates an object of that class and registers it
as the listener for changes to the tipPercentageSlider 's value.
The call to method valueProperty (line 68) returns an object of class DoubleProp-
erty (package javax.beans.property ) that represents the Slider 's value. A DoublePro-
perty is an ObservableValue that can notify listeners when the value changes. Each class
that implements interface ObservableValue provides method addListener (called on line
68) for registering a ChangeListener . In the case of a Slider 's value, addListener 's argu-
ment is an object that implements ChangeListener<Number> , because the Slider 's value
is a numeric value.
Since an anonymous inner class has no name, one object of the class must be created
at the point where the class is declared (starting at line 69). Method addListener 's argu-
ment is defined in lines 69-79 as a class-instance creation expression that declares an anon-
 
Search WWH ::




Custom Search