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();
user1803551
  • 12,965
  • 5
  • 47
  • 74
msj121
  • 2,812
  • 3
  • 28
  • 55

2 Answers2

26

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;
    }
};
user1803551
  • 12,965
  • 5
  • 47
  • 74
msj121
  • 2,812
  • 3
  • 28
  • 55
12

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.

user1803551
  • 12,965
  • 5
  • 47
  • 74
  • 1
    Great answer !! First time i have seen `ListExpression` https://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/ListExpression.html – GOXR3PLUS Feb 08 '17 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. – user1803551 Feb 08 '17 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 Feb 08 '17 at 14:39
  • 1
    @GOXR3PLUS `SimpleListProperty` is enough for this. – user1803551 Feb 08 '17 at 14:50