Java Reference
In-Depth Information
the value is changed in the Observable object, the listener is notified by invoking its
invalidated(Observable  o) method. Every binding property is an instance of
Observable . Listing  15.10 gives an example of observing and handling a change in a
DoubleProperty object balance .
observable object
L ISTING 15.10
ObservablePropertyDemo.java
1 import javafx.beans.InvalidationListener;
2 import javafx.beans.Observable;
3 import javafx.beans.property.DoubleProperty;
4 import javafx.beans.property.SimpleDoubleProperty;
5
6 public class ObservablePropertyDemo {
7 public static void main(String[] args) {
8 DoubleProperty balance = new SimpleDoubleProperty();
9 balance.addListener( new InvalidationListener() {
10 public void invalidated(Observable ov) {
11 System.out.println( "The new value is " +
12 balance.doubleValue());
13 }
14 });
15
16 balance.set( 4.5 );
17 }
18 }
observable property
add listener
handle change
The new value is 4.5
When line 16 is executed, it causes a change in balance, which notifies the listener by
invoking the listener's invalidated method.
Note that the anonymous inner class in lines 9-14 can be simplified using a lambda expres-
sion as follows:
balance.addListener(ov -> {
System.out.println( "The new value is " +
balance.doubleValue());
});
Recall that in Listing 14.20 DisplayClock.java, the clock pane size is not changed when
you resize the window. The problem can be fixed by adding a listener to change the clock
pane size and register the listener to the window's width and height properties, as shown in
Listing 15.11.
L ISTING 15.11
DisplayResizableClock.java
1 import javafx.application.Application;
2 import javafx.geometry.Pos;
3 import javafx.stage.Stage;
4 import javafx.scene.Scene;
5 import javafx.scene.control.Label;
6 import javafx.scene.layout.BorderPane;
7
8 public class DisplayResizableClock extends Application {
9 @Override // Override the start method in the Application class
10 public void start(Stage primaryStage) {
11 // Create a clock and a label
12 ClockPane clock = new ClockPane();
13 String timeString = clock.getHour() + ":" + clock.getMinute()
14 + ":" + clock.getSecond();
 
Search WWH ::




Custom Search