Java Reference
In-Depth Information
case 4: selectedDBs.setValue(120);
break;
case 5: selectedDBs.setValue(130);
}
});
}
}
Using InvalidationListeners and Lambda Expressions
In the earlier section “The Magic of Binding,” we showed how you can use property binding for dynamically changing
parameters. There is another, more low-level but also more flexible way of achieving this, using ChangeListeners and
InvalidationListeners . These concepts are discussed in more detail in Chapter 4.
In our example, we add an InvalidationListener to the selectedIndexProperty of the genreSelectionModel .
When the value of the selectedIndexProperty changes, and when we didn't retrieve it yet, the
invalidated(Observable) method on the added InvalidationListener will be called. In the implementation of this
method, we retrieve the value of the selectedIndexProperty , and based on its value, the value of the selectedDBs
property is changed. This is achieved with the following code:
public void addListenerToGenreSelectionModel() {
genreSelectionModel.selectedIndexProperty().addListener((Observable o) -> {
int selectedIndex = genreSelectionModel.selectedIndexProperty().getValue();
switch(selectedIndex) {
case 0: selectedDBs.setValue(80);
break;
case 1: selectedDBs.setValue(100);
break;
case 2: selectedDBs.setValue(150);
break;
case 3: selectedDBs.setValue(140);
break;
case 4: selectedDBs.setValue(120);
break;
case 5: selectedDBs.setValue(130);
}
});
}
Note that we are using a Lambda expression here rather than creating a new instance of the
InvalidationListener and implementing its single abstract method invalidated.
One of the major enhancements in JavaFX 8 is the fact that it is using Java 8. as a consequence, abstract
classes with a single abstract method can easily be replaced by Lambda expressions, which clearly enhances readability
of the code.
Tip
 
 
Search WWH ::




Custom Search