【问题标题】:How to create and add a style class dynamically in javafx [closed]如何在 javafx 中动态创建和添加样式类 [关闭]
【发布时间】:2017-06-07 06:15:30
【问题描述】:

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

【问题讨论】:

  • 备案:我知道 setStyle 方法,但在这种情况下我不能使用它。
  • 为什么不能用?
  • 我用的是第三方库,没有setStyle的API。
  • 如果它是一个JavaFX Node(或它的任何子类),它有一个setStyle(...) 方法和一个getStyleClass() 方法。如果它不是Node 的子类,则无论如何都不能将它放在ScenePane 中。请清楚你的意思。

标签: css javafx


【解决方案1】:

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

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

.my-new-style-class {
    -fx-padding: 5;
}

【讨论】:

  • 不,我想在代码中定义一个样式类,而不是css文件。
【解决方案2】:

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

这是一个工作示例:

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

【讨论】:

    【解决方案3】:

    嗯,已经晚了,晚了 2 年,但也许它对某人有帮助。

    想法是这样的:

    object.setStyle("[your CSS code]"); 
    

    为名为“node”的对象赋予红色背景色的示例:

    node.setStyle("fx-background-color: red"); 
    

    我希望它对某人有所帮助。

    【讨论】:

    • node.setStyle("-fx-background-color: red");
    猜你喜欢
    • 2013-04-20
    • 1970-01-01
    • 2017-11-26
    • 2021-11-10
    • 2010-10-05
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多