在 JavaFX 中是否可以不使用节点的父样式表?

Is it possible in JavaFX to not use the parent StyleSheet of a Node?

我想创建一个 JavaFX 节点层次结构,例如:

Region parentRegion = new Region();
Circle circle = new Circle();
parentRegion.getChildren().add(circle);

但是我不希望父区域的子区域使用父区域的样式表。

例如,如果我有以下 CSS:

.green {
  -fx-fill: green;
}

我有以下代码:

Region parentRegion = new Region();
parentRegion.getStylesheets().add(<my CSS path>);
Circle circle = new Circle();
circle.getStyleClass().add("green");
parentRegion.getChildren().add(circle);

我希望圆圈是黑色而不是绿色。

可能吗?

您可以将 child 放在 SubScene 中。

子场景不继承其 parent 节点的 CSS 样式。

例子

示例中有两个圆圈,一个在主场景的根布局窗格中,另一个在SubScene(浅蓝色背景)中,该子场景也在主场景的根布局窗格中主场景

主场景(VBox)的布局窗格定义了样式,因此所有 child 圆都继承了绿色填充。但是,SubScene 阻止了 CSS 样式的继承,因此只有不在 SubScene 中的圆圈是绿色的。

colored-circles.css

.green {
    -fx-fill: green;
}

Circle {
    -fx-fill: inherit;
}

请注意,默认情况下,-fx-fill CSS 属性值不会被 child 节点继承,因此附加规则让圆继承 CSS 属性值对于 -fx-fill.

StyleInheritance.java

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class StyleInheritance extends Application {

    public static final double R = 50;

    @Override
    public void start(Stage stage) {
        Circle circleInMainScene = new Circle(R, R, R);
        Circle circleInSubScene = new Circle(R, R, R);

        SubScene subScene = new SubScene(
                new Group(circleInSubScene),
                circleInSubScene.getLayoutBounds().getWidth(),
                circleInSubScene.getLayoutBounds().getHeight()
        );
        subScene.setFill(Color.LIGHTBLUE);

        VBox layout = new VBox(10, circleInMainScene, subScene);
        layout.setPadding(new Insets(10));
        layout.getStyleClass().add("green");

        Scene mainScene = new Scene(layout);

        mainScene.getStylesheets().add(
                StyleInheritance.class.getResource(
                        "colored-circles.css"
                ).toExternalForm()
        );

        stage.setScene(mainScene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

可能还有一些方法可以单独通过 CSS 规则而不是使用 SubScene 来完成您想要的,但是使用 SubScene 似乎可行,这就是我想出的。