我有一个模型类,其中包含 IntegerProperty 类型的十进制 RGB 值成员(即值 16777215,#FFFFFF,白色)。现在我需要将它绑定(bind)到 ColorPicker 控件,但它需要 ObservableValue<Color>
我不知道如何“转换” IntegerProperty
至ObservableValue<Color>
并成功绑定(bind)到ColorPicker。
有什么好主意来实现吗?
提前致谢。
最佳答案
也许有更好的解决方案,但这会创建颜色和整数属性的双向绑定(bind)。
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);
这是从 Color 到 int 的转换。 (受到 WritableImage 中 PixelWriter
方法 setColor
的启发)
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;
}
这是从 int 到 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);
}
关于JavaFX - 如何将 IntegerProperty 中的 RGB 值绑定(bind)到 ColorPicker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49255738/