Java Reference
In-Depth Information
ymous inner class and creates one object of that class. A reference to that object is then
passed to addListener . After the new keyword, the syntax ChangeListener<Number>()
(line 69) begins the declaration of an anonymous inner class that implements interface
ChangeListener<Number> . This is similar to beginning a class declaration with
public class MyHandler implements ChangeListener<Number>
The opening left brace at 70 and the closing right brace at line 79 delimit the body of
the anonymous inner class. Lines 71-78 declare the ChangeListener<Number> 's changed
method, which receives a reference to the ObservableValue that changed, a Number con-
taining the Slider 's old value before the event occurred and a Number containing the
Slider 's new value. When the user moves the Slider 's thumb, lines 75-76 store the new
tip percentage and line 77 updates the tipPercentageLabel .
An anonymous inner class can access its top-level class's instance variables, static
variables and methods—in this case, the anonymous inner class uses instance variables
tipPercentage and tipPercentageLabel , and static variable percent . However, an
anonymous inner class has limited access to the local variables of the method in which it's
declared—it can access only the final local variables declared in the enclosing method's
body. (As of Java SE 8, an anonymous inner class may also access a class's effectively final
local variables—see Section 17.3.1 for more information.)
Java SE 8: Using a Lambda to Implement the ChangeListener
Recall from Section 10.10 that in Java SE 8 an interface containing one method is a func-
tional interface and recall from Chapter 17 that such interfaces may be implemented with
lambdas. Section 17.9 showed how to implement an event-handling functional interface
using a lambda. The event handler in Fig. 25.21 can be implemented with a lambda as
follows:
tipPercentageSlider.valueProperty().addListener(
(ov, oldValue, newValue) ->
{
tipPercentage =
BigDecimal.valueOf(newValue.intValue() / 100.0 );
tipPercentageLabel.setText(percent.format(tipPercentage));
});
25.6 Features Covered in the Online JavaFX Chapters
JavaFX is a robust GUI, graphics and multimedia technology. In the online Chapters 26
and 27, you'll:
Learn additional JavaFX layouts and controls.
Handle other event types (such as MouseEvent s).
Apply transformations (such as moving, rotating, scaling and skewing) and effects
(such as drop shadows, blurs, reflection and lighting) to a scene graph's nodes.
Use CSS to specify the look-and-feel of controls.
Use JavaFX properties and data binding to enable automatic updating of controls
as corresponding data changes.
Use JavaFX graphics capabilities.
 
 
Search WWH ::




Custom Search