But sometimes you want to bind to a property of an object, that is held in another property. Lets make an example. You have a property selectedCustomer which holds a Customer object. In that Customer object you have a String property called name. If you bind directly to name with bind(selectedCustomer.get().nameProperty()) you get in trouble, if the value of selectedCustomer changes. Of course you can fix that with implementing a ChangeListener and add it to selectedCustomer and rebind it on the change.
Here is a class, that encapsulated that for you, here is the code for your free use:
This is a Java 8 example and makes use of the new Lamda features. Of course you can use that with replacing the lambdas with anonymous inner classes.
The use is very easy:
ObjectProperty<Customer> selectedCustomer =...;
ObjectProperty<String> selectedName = new NestedObjectProperty<>(selectedCustomer,
(Customer customer)-> customer.nameProperty(), false);
The Parameters of the constructor are:
- The property that delivers the property to bind against, in our example selectedCustomer
- A Function implementation, that returns the property to bind against, in our example it gets a Customer as parameter and returns a String property
- A boolean, if the binding should be unidirectional or bidirectional