Search code examples
javafxpropertiesbindingtableviewbidirectional

JavaFx: Bidirectional Binding, selected value in TableView


I need some help, im trying to bind properties of an object in my model with some labels and textfields.

label1.textProperty().bind(myModel.getSelectedObject().getNameProperty());

in this case getSelectedObject() is the selected Object in a TableView. Somehow this doesn't work as expected. When the model's value changes, the label doesn't change.

I mangaged to fix this issue with the Bindings help class:

label1.textProperty().bind(Bindings.select(myModel.getSelectedObject(), "name"));

Only with the Bindings help class the label's text gets binded correctly to the name-property of the object.

now im trying to get the same result with a bidirectional binding. Anyone any ideas?

If i bind it like this, it has no effect (same as first code-snipped)

textField.textProperty().bindBidirectional(myModel.getSelectedObject().getNameProperty());

Solution

  • ChangeListener for SelectionModel enable to switch binding. Try it out.

    tableView.getSelectionModel().selectedItemProperty().addListener((o, ov, nv) -> {
        if (ov != null) textField.textProperty().unbindBidirectional(ov.nameProperty());
        if (nv != null) {
            textField.setDisable(false);
            textField.textProperty().bindBidirectional(nv.nameProperty());
        } else {
            textField.setDisable(true);
            textField.setText("");
        }
    });
    

    NOTE:

    In case selected item is removed from TableView's items, This ChangeListner is called with removed item as oldValue rather than null. So no needs to care removal of list item .