9

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();

2 Answers 2

27

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;
    }
};
13

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.

4
  • 1
    Great answer !! First time i have seen ListExpression docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/…
    – GOXR3PLUS
    Commented Feb 8, 2017 at 12:58
  • @GOXR3PLUS You will probably never see 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
  • Already added it into the code :) . I need to bind the maximum value of a ScrollBar to the Size of an Observable List - 1
    – GOXR3PLUS
    Commented Feb 8, 2017 at 14:39
  • 2
    @GOXR3PLUS SimpleListProperty is enough for this. Commented Feb 8, 2017 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.