我正在尝试将外部.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");
那不会被拾起。
我可能做错了什么?
先感谢您。
最佳答案
不要尝试自己将文件名转换为URL
。而是使用File
类的内置方法:
scene.getStylesheets().setAll(f.toURI().toURL().toExternalForm());
假设运行应用程序时文件位于相对于当前工作目录的指定路径。在大多数情况下,使用相对文件路径是个坏主意,因为从其他目录运行会破坏程序。最好将css文件作为资源包括在内。