I've got a model class with a decimal RGB value member (i.e. value 16777215, #FFFFFF, which is white) in IntegerProperty type. Now I need to bind it to ColorPicker control but it needs ObservableValue<Color>
and I don't know how to "convert" the IntegerProperty
to ObservableValue<Color>
and successfully bind it to the ColorPicker.
Any good idea for implementing that?
Thanks in advance.
Maybe there is a better solution, but this creates bidirectional binding of color and integer properties.
IntegerProperty intProperty = new SimpleIntegerProperty();
ObjectProperty<Color> colorProperty = colorPicker.valueProperty();
ObjectBinding<Color> colorBinding = Bindings.createObjectBinding(() -> intToColor(intProperty.get()), intProperty);
colorProperty.bind(colorBinding);
IntegerBinding intBinding = Bindings.createIntegerBinding(() -> colorToInt(colorProperty.get()), colorProperty);
intProperty.bind(intBinding);
Here is a conversion from Color to int. (Inspired by method setColor
of PixelWriter
in WritableImage)
private int colorToInt(Color c) {
int r = (int) Math.round(c.getRed() * 255);
int g = (int) Math.round(c.getGreen() * 255);
int b = (int) Math.round(c.getBlue() * 255);
return (r << 16) | (g << 8) | b;
}
And here is a conversion from int to Color. (More about splitting of an integer)
private Color intToColor(int value) {
int r = (value >>> 16) & 0xFF;
int g = (value >>> 8) & 0xFF;
int b = value & 0xFF;
return Color.rgb(r,g,b);
}