Binding to properties of an object which is itself wrapped in a property seems like something one does a lot in typical applications, is there a better way to do this in JavaFX than what I do below?
Some more details to explain: I want to make GUI in JavaFX 2.2, for managing a number of items. I've created a small example to test everything, in which the items are persons. The set of persons is shown in a custom way (not a list or tree, but I don't think that matters here), and I can select a single one.
In a side panel I can edit the currently selected person. Updates are immediately visible in the set of persons, and when I select another person, the edit panel is updated.
JavaFX's bidirectional binding seems perfect for this purpose. I currently have this for the fx:controller of the "person editing" Pane:
public class PersonEditor implements ChangeListener<Person> {
@FXML private TextField nameField;
@FXML private TextField ageField;
@FXML private TextField heightField;
public void setSelection(ObjectProperty<Person> selectedPersonProperty) {
selectedPersonProperty.addListener(this);
}
@Override
public void changed(ObservableValue<? extends Person> observable, Person oldVal, Person newVal) {
if (oldVal != null) {
nameField.textProperty().unbindBidirectional(oldVal.nameProperty());
ageField.textProperty().unbindBidirectional(oldVal.ageProperty());
heightField.textProperty().unbindBidirectional(oldVal.heightProperty());
}
if (newVal != null) {
nameField.textProperty().bindBidirectional(newVal.nameProperty());
ageField.textProperty().bindBidirectional(newVal.ageProperty());
heightField.textProperty().bindBidirectional(newVal.heightProperty());
}
}
}
I'm wondering if there is a nicer way, perhaps something in JavaFX to do bind to properties of an object that can change? I don't like the fact that I have to manually unbind all properties, it feels like duplicate code. Or is this as simple as it can be in JavaFx?