Bidirectional Binding for Selection Model

I do not know why the JavaFX developers have not included this in the existing toolset, so I created this by myself based on the JavaFX BidirectionalBinding class: A BidirectionalBinding between a SelectionModel and an ObjectProperty.

Whenever the ObjectProperty changes, the selection is updated and when the selection changes the ObjectProperty is updated. I posted the code at Github.

Usage is typically by a static factory method, so here you go:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static <T> void bindBidirectional(Property<T> pProperty,
      SelectionModel<T> pSelectionModel, boolean pInitialValueFromSelection) {

  SelectionModelBidirectionalBinding<T> binding = new SelectionModelBidirectionalBinding<>(
          pProperty, pSelectionModel);
  if (pInitialValueFromSelection) {
      pProperty.setValue(pSelectionModel.getSelectedItem());
  } else {
      pSelectionModel.select(pProperty.getValue());
  }
  pProperty.addListener(binding);
  pSelectionModel.selectedItemProperty().addListener(binding);
}

This method differs a little bit from the default JavaFX BidirectionalBindings by adding a third argument: The boolean argument is to decide where the initial value should be extracted from: Either from the ObjectProperty or the SelectionModel.

Comments