如何将css添加到JavaFx元素

时间:2017-01-13 19:49:19

标签: java css javafx

我尝试将外部 .css 文件添加到Java FX场景图中,如下所示:

File f = new File("../theming/css/test.css");
scene.getStylesheets().clear();
scene.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));

test.css

.custom-background {
    -fx-background-color: #1d1d1d;
    -fx-background-color: red;
    -fx-padding: 15;
    -fx-spacing: 10;
}

.label {
    -fx-font-size: 11pt;
    -fx-font-family: "Segoe UI Semibold";
    -fx-text-fill: white;
    -fx-opacity: 0.6;
}

除了我尝试向元素添加自定义类的地方外,样式类得到了很好的添加:

Hbox hbox = new HBox();
hbox.setSpacing(10);
hbox.setMinSize(400, 300);
hbox.getStyleClass().add("custom-background");

那不会被接受。

我可能做错了什么?

提前谢谢。

1 个答案:

答案 0 :(得分:4)

请勿尝试自己将文件名转换为URL。而是使用File类的构建方法:

scene.getStylesheets().setAll(f.toURI().toURL().toExternalForm());

这假设文件位于运行应用程序时相对于当前工作目录的指定路径。在大多数情况下,使用相对文件路径是一个坏主意,因为从不同的目录运行会破坏程序。最好将css文件包含为资源。