Search code examples
javafxbackgroundcolor-picker

Binding ColorPicker in JavaFX to Label Background property


Works well for foreground by simply:

    ObjectProperty op = label.textFillProperty();
    ColorPicker cp = new ColorPicker(Color.GRAY);   
    ...             
    op.bind(cp.valueProperty());

How do I do it for Background - not even sure it is possible, due to the complexity of Background property


Solution

  • First, don't use raw types. The code you posted should be

    ObjectProperty<Paint> op = label.textFillProperty();
    ColorPicker cp = new ColorPicker(Color.GRAY);   
    ...             
    op.bind(cp.valueProperty());
    

    For the background you can use Bindings.createObjectBinding():

    ObjectProperty<Background> background = label.backgroundProperty();
    background.bind(Bindings.createObjectBinding(() -> {
        BackgroundFill fill = new BackgroundFill(cp.getValue(), CornerRadii.EMPTY, Insets.EMPTY);
        return new Background(fill);
    }, cp.valueProperty());