I want to bind a value to the ObservableList
's size to know its size and also to know if it has multiple values
private ObservableList<String> strings = FXCollections.observableArrayList();
They can be bound with the Bindings
class:
ObservableList<String> strings = FXCollections.observableArrayList();
IntegerBinding sizeProperty = Bindings.size(strings);
BooleanBinding multipleElemsProperty = new BooleanBinding() {
@Override protected boolean computeValue() {
return strings.size() > 1;
}
};
The accepted answer is correct. I will provide additional insight for the benefit of interested readers.
ObservableList
is an interface and as such does not hold a size
property.
ListExpression
is an abstract class implementing ObservableList
and adding ReadOnlyIntegerProperty size
and
ReadOnlyBooleanProperty empty
properties. This class is the base class for a whole inheritance tree of list properties classes.
Most users will not want to subclass the abstract classes in the tree themselves, so we'll look at the provided concrete implementation:
ListExpression (abstract)
- ReadOnlyListProperty (abstract)
- ListProperty (abstract)
- ListPropertyBase (abstract)
- SimpleListProperty
- ReadOnlyListWrapper
SimpleListProperty
is, as its name suggests, a simple list property - an ObservableList
wrapped in a Property
. It is the parallel of the other SimpleXxxProperty
s. It also has a subclass
ReadOnlyListWrapper
to handle read-only and read-and-write requirements. It can be constructed from an ObservableList
:
SimpleListProperty<String> list = new SimpleListProperty<>(FXCollections.observableArrayList());
IntegerProperty intProperty = new SimpleIntegerProperty();
intProperty.bind(list.sizeProperty());
Users which need the benefits from this class (over just using ObservableList
) and decide to use it do not need the static Bindings#size
approach.
ListExpression
docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/…
Commented
Feb 8, 2017 at 12:58
ListExpression
in code since it's very low level and few will need to use it directly. SimpleListProperty
and ReadOnlyListWrapper
, on the other hand, are quite useful out-of-the-box.
Commented
Feb 8, 2017 at 13:07
Observable List - 1
Commented
Feb 8, 2017 at 14:39