在JAVAFX中扩展CSS样式

在JAVAFX中扩展CSS样式

本文介绍了在JAVAFX中扩展CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JAVAFX应用程序中使用CSS. CSS文件中是否有一种方法可以利用某种继承?例如,我有一种样式称为红线":

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

这样绿色"线的笔划宽度为5px?预先感谢!

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

推荐答案

您需要提供一个更具体的选择器.您可以例如添加样式类:

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

将样式类line添加到所有行,然后还将redblue样式类添加到应获得这些颜色的行.

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.

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;
}

在CSS中,更具体的规则将始终覆盖较不具体的规则的属性.在这种情况下,.line的定义不如.line.blue.line.red明确,因为前一个选择器仅包含一个类,而不是2.

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.

注意: CSS中有继承关系,但是属性是从场景中的父级继承的,而不是从Java代码中的基类继承的.

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.

这篇关于在JAVAFX中扩展CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:31