JavaFX How to - Bind Object Property








Question

We would like to know how to bind Object Property.

Answer

/*  w  w  w  .  j  a  v a2s .co  m*/
import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;
import javafx.scene.paint.Color;

public class Main {
    public static void main(String[] args) {
        ObjectProperty<Lighting> root = new SimpleObjectProperty<Lighting>();
        final ObjectBinding<Color> colorBinding = Bindings.select(root, "light", "color");
        colorBinding.addListener(new ChangeListener<Color>() {
            @Override
            public void changed(ObservableValue<? extends Color> observableValue, Color oldValue, Color newValue) {
                System.out.println(oldValue + "new = " + newValue);
            }
        });
        Light firstLight = new Light.Point();
        firstLight.setColor(Color.BLACK);

        Light secondLight = new Light.Point();
        secondLight.setColor(Color.WHITE);

        Lighting firstLighting = new Lighting();
        firstLighting.setLight(firstLight);

        root.set(firstLighting);
        firstLighting.setLight(firstLight);
        firstLight.setColor(Color.RED);
    }
}