我正在尝试将外部 .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 文件作为资源包含在内。
关于java - 如何将 css 添加到 JavaFx 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41642403/