3 Replies Latest reply: May 9, 2012 5:56 AM by 895058 RSS

    Size property for an ObservableList

    796211
      Hi all.

      I'm probably doing something stupid but I can't find the size property of an ObservableList.

      I want to do something like this:
      tabPane.getSelectionModel().selectedIndexProperty().greaterThan(tabPane.getTabs().sizeProperty())
      so that I get a BooleanBinding that is false if the last tab is selected, true otherwise.

      sizeProperty doesn't seem to exist though. Any one got any ideas how I can do this?

      Thanks, Nick.
        • 1. Re: Size property for an ObservableList
          Richard Bair-Oracle
          Great question. This seems like a definite missing piece, unfortunately ObservableList is an interface and we can't add a sizeProperty method -- until Java 8 anyway (with defender methods or whatever they end up calling them).

          Another way to get what you want is to use the low-level binding API.
                  final TabPane pane = new TabPane();
                  final SelectionModel sm = pane.getSelectionModel();
                  final ObservableList<?> tabs = pane.getTabs();
                  BooleanBinding binding = new BooleanBinding() {
                      { bind(sm.selectedIndexProperty(), tabs); }
                      @Override protected boolean computeValue() {
                          return sm.getSelectedIndex() == tabs.size() - 1;
                      }
                  };
          I added in the final references to sm and tabs just for clarity in the example. Basically we create the BooleanBinding, in the initializer we call "bind" and pass Observables that we want to pay attention to. Whenever they change, we are notified and recompute. An ObservableList is an Observable, so we can get notified whenever it changes, which will invalidate this binding, and then end up causing computeValue to be called on the next time the binding's value is read. In this case, we simply compute as needed in the computeValue whether the value is true or false (assuming i got the logic of the method right!).

          Richard
          • 2. Re: Size property for an ObservableList
            796211
            Hi Richard.

            That looks good.

            Thanks for the info,

            Nick.
            • 3. Re: Size property for an ObservableList
              895058
              Hi Richard,

              your answer is not fully correct. :-) The Bindings class provides something for the sizeProperty as high level API. The code would look something like this:
              tabPane.getSelectionModel().selectedIndexProperty().greaterThan(Bindings.size(tabPane.getTabs()))
              Btw. ListExpressions, which were added in 2.1, have a size-property. Maybe we should consider migrating our properties of type ObservableList to one of the ListProperty implementations.