如何在运行时覆盖(编辑)CSS颜色?

时间:2017-04-17 16:08:46

标签: css javafx colors

我想让用户通过“设置”菜单编辑应用UI颜色。 默认颜色在.css文件中定义,例如:

.vertex {
   -fx-fill: rgba(64, 196, 255, 1);
}

在上面的示例中,我想要将-fx-fill颜色覆盖为用户从颜色拾取对话框中选择的颜色。是否可以在运行时更新CSS类属性?怎么样?

1 个答案:

答案 0 :(得分:1)

您可以在CSS文件中使用查找颜色:

.vertex {
    -vertex-fill: rgba(64, 196, 255, 1);
    -fx-fill: -vertex-fill ;
}

然后您可以使用内联样式在运行时修改它。您可以在组件的任何祖先上调用setStyle(),它将适用于所有后代组件。例如。要将更改应用于样式类为.vertex的场景中的所有内容,请设置场景的根样式:

Color selectedColor = colorPicker.getValue();
int red = (int) (255 * selectedColor.getRed());
int green = (int) (255 * selectedColor.getGreen());
int blue = (int) (255 * selectedColor.getBlue());
double opacity = selectedColor.getOpacity();
String userColor = String.format("rgba(%d, %d, %d, %f)", red, green, blue, opacity) ;
scene.getRoot().setStyle("-vertex-fill: " + userColor + " ;");
相关问题