extending CSS style in JAVAFX

天涯浪子 提交于 2020-04-16 06:35:53

问题


I' m trying to use CSS in JAVAFX application. Is there a way in the CSS file to make use of some kind of inheritance? For example I have one style called "redline":

.redline{
    -fx-stroke:red;
    -fx-stroke-width:5px;
}

Can I create a second style "greenline":

.greenline{
    -fx-stroke:green;
}

in a way that it inherits from "redline". Say, something like:

greenline extends redline

so that the "green" lines have a strokewidth of 5px? Thanks in advance!


回答1:


You need to make a make a more specific selector available. You could e.g. add a style class:

Add the style class line to all lines and then also add the red or blue style classes to the lines that should get those colors.

Example

Java Code

Line redLine = ...
redLine.getStyleClass().add("line");
Line blueLine = ...
blueLine.getStyleClass().add("line");
Line blackLine = ...
blackLine.getStyleClass().add("line");

// add color related classes
redLine.getStyleClass().add("red");
blueLine.getStyleClass().add("blue");

...

CSS

.line {
    -fx-stroke: black; /* define standard line color */
    -fx-stroke-width: 5px;
}

.line.blue { /* rules for nodes that have style classes line AND blue */
    -fx-stroke: blue;
}

.line.red { /* rules for nodes that have style classes line AND red */
    -fx-stroke: red;
}

In CSS more specific rules will always overwrite properties of less specific rules. In this case .line is less specific than .line.blue and .line.red since the former selector contains only a single class instead of 2.


Note: There is inheritance in CSS, but properties are inherited from the parent in the scene, not from the base class in the java code.



来源:https://stackoverflow.com/questions/43310053/extending-css-style-in-javafx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!