Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a value to an ObservableList's size?

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();
like image 732
msj121 Avatar asked Jul 23 '15 18:07

msj121


2 Answers

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;
    }
};
like image 97
msj121 Avatar answered Nov 05 '22 06:11

msj121


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.

like image 22
user1803551 Avatar answered Nov 05 '22 05:11

user1803551