如何在运行时覆盖(编辑)CSS颜色?(How to override (edit) CSS colors at runtime?)

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

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

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

I want to make possible for users edit app UI colors via Settings menu. Default colors are defined in .css file, for example:

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

In the example above I want to override -fx-fill color to whatever the user will choose from a color pickup dialog. Is it possible to update at runtime CSS class attribute ? How ?

最满意答案

您可以在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 + " ;");

You can use a looked-up color in the CSS file:

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

and then you can modify it at runtime using an inline style. You can call setStyle() on any ancestor of the components, and it will apply to all descendant components. E.g. to apply the change to everything in a scene with style class .vertex, set the style of the scene's root:

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 + " ;");

更多推荐