JavaFX - 如何将IntegerProperty中的RGB值绑定到ColorPicker?

时间:2018-03-13 12:05:04

标签: java user-interface javafx javafx-8 color-picker

我在IntegerProperty类型中有一个带有十进制RGB值成员的模型类(即值16777215,#FFFFFF,它是白色)。现在我需要将它绑定到ColorPicker控件但它需要ObservableValue<Color>并且我不知道如何转换&#34; IntegerPropertyObservableValue<Color>并成功将其绑定到ColorPicker。

实施这个有什么好主意吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

如果您已将代码固定为将整数转换为颜色,反之亦然(您可能有),这里是转换部分:

// I assume you have some method like this somewhere
private static Color int2color(int intVal) {
    return ...
}

// your property
SimpleIntegerProperty iob = new SimpleIntegerProperty(0);

// The conversion. Note that ObjectBinding<Color> is derived from ObservableValue<Color>
ObjectBinding<Color> colorBinding = Bindings.createObjectBinding(() -> int2color(iob.get()), iob);

答案 1 :(得分:1)

也许有更好的解决方案,但这会创建颜色和整数属性的双向绑定。

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中的setColor方法PixelWriter

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);
}
相关问题