0

I would like to bidirectionaly bind a color property with r, g, b fields and also a ColorPicker. Here is what I have:

private IntegerProperty r = new SimpleIntegerProperty(); private IntegerProperty g = new SimpleIntegerProperty(); private IntegerProperty b = new SimpleIntegerProperty(); private ObjectProperty<Color> color = new SimpleObjectProperty<>(); ColorPicker colorPicker = new ColorPicker(); // Bind the colorPicker and 'color' colorPicker.valueProperty().bindBidirectional(color); 

Now I need to bind the color and split it in r, g, b. I know I can start with something like this (unidirectional):

color.bind(Bindings.createObjectBinding( () -> Color.rgb(r.get(), g.get(), b.get()), r, g, b )); 

But Java throws an exception A bound value cannot be set. Is there another way to do it or should I use listeners? Thank you!

2
  • What's your aim? Do you want to be able to do, for example, r.set(128), and have color (and consequently the color picker) update? And if the user chooses a color in the color picker, do you want r, g, and b to be updated? I think you would have to use at least some listeners for that. Commented May 18, 2017 at 16:56
  • @James_D Yes, exactly. I know it's overkill to have r, g and b as I can get them through color but I have special needs. Thank you I will try with a listener. Commented May 18, 2017 at 17:02

1 Answer 1

1

If you want all of these properties to be consistent, and want to be able to change any of them independently (and have the others update as necessary), then you can only use bidirectional bindings and listeners (not one-way bindings, which don't allow the bound value to be set as that would violate the binding). One possible way would be:

ChangeListener<Number> componentListener = (obs, oldValue, newValue) -> color.set(Color.rgb(r.get(), g.get(), b.get()); r.addListener(componentListener); g.addListener(componentListener); b.addListener(componentListener); color.addListener((obs, oldColor, newColor) -> { r.set((int)/(256*newColor.getRed())); g.set((int)/(256*newColor.getGren())); b.set((int)/(256*newColor.getBlue())); }); colorPicker.valueProperty().bindBidirectional(color); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.