14

I have a TableView and I would like to bind the disable property of a Button with the size of the ObservableList model of the table. In particular, I would like to disable the button when the size of the ObservableList is grater than 2.

How can I achieve that?

To disable another button when no row is selected in table I used

editRoadButton.disableProperty().bind(roadsTable.getSelectionModel().selectedItemProperty().isNull());

Is there a similar way?

Giorgio
  • 1,973
  • 4
  • 36
  • 51

2 Answers2

22

There are factory methods for useful bindings in the Bindings class. In your case f.i.:

button.disableProperty().bind(Bindings.size(items).greaterThan(2));
kleopatra
  • 51,061
  • 28
  • 99
  • 211
2

You can do something like that

ListProperty<String> list = new SimpleListProperty<>(FXCollections.<String>emptyObservableList());
Button foo = new Button();

foo.disableProperty().bind(new BooleanBinding() {
    {
        bind(list);
    }

    @Override
    protected boolean computeValue() {
        return list.size() > 2;
    }
});
agonist_
  • 4,890
  • 6
  • 32
  • 55
  • What about memory leaks? I have to call unbind? Where? – Giorgio Jun 17 '14 at 08:45
  • Personnaly I do my bindings on a configure() method, and unbind everything on unconfigure() method. It's depend how your program is done but my unconfigure are called when I changed the view to another. It's the same if you add listner, you have to remove them – agonist_ Jun 17 '14 at 08:47