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 SimpleXxxPropertys. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With