如何在javafx中动态创建和添加样式类

Ami*_*avi 2 css javafx

我想用 java 代码(不在样式表文件中)创建一个样式类并将其添加到 javafx 节点。

Jai*_*Jai 8

不确定这是否是您要找的...

Button node = new Button();
node.getStyleClass().add("my-new-style-class");

.my-new-style-class {
    -fx-padding: 5;
}
Run Code Online (Sandbox Code Playgroud)

  • 不,我想在代码中定义一个样式类,而不是一个 css 文件。 (3认同)

DVa*_*rga 5

这个想法是创建一个临时 stlyesheet 文件,在里面写入新的样式类,将样式表添加到节点的工作表列表中,并添加新的样式类。

这是一个工作示例:

Button button = new Button("My Text");

button.setOnAction(e -> {

    try {
        // Create a new tempfile that will be removed as the application exits
        File tempStyleClass = File.createTempFile("AppXY_TempStyleClass", ".css");
        tempStyleClass.deleteOnExit();

        // Write the stlye-class inside
        try (PrintWriter printWriter = new PrintWriter(tempStyleClass)) {
            printWriter.println(".temp-style { -fx-text-fill: red; }");
        }

        // Add the style-sheet and the style-class to the node
        button.getStylesheets().add(tempStyleClass.toURI().toString());
        button.getStyleClass().add("temp-style");

    } catch (IOException e1) {
        e1.printStackTrace();
    }
});
Run Code Online (Sandbox Code Playgroud)