[英]How to add css to a JavaFx element
I'm trying to add a an external .css file to a Java FX scene graph as follows: 我正在尝试将外部.css文件添加到Java FX场景图,如下所示:
File f = new File("../theming/css/test.css");
scene.getStylesheets().clear();
scene.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));
test.css 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;
}
The style classes get added well, except where I try to add a custom class to an element: 样式类添加得很好,除非我尝试在元素中添加自定义类:
Hbox hbox = new HBox();
hbox.setSpacing(10);
hbox.setMinSize(400, 300);
hbox.getStyleClass().add("custom-background");
That doesn't get picked up. 那不会被拾起。
What could I be doing wrong? 我可能做错了什么?
Thank you in advance. 先感谢您。
Don't try to convert the file name to a URL
yourself. 不要尝试自己将文件名转换为URL
。 Instead use the build in methods of the File
class: 而是使用File
类的内置方法:
scene.getStylesheets().setAll(f.toURI().toURL().toExternalForm());
This assumes the file is located at the specified path relative to the current working directory when the application is run. 假设运行应用程序时文件位于相对于当前工作目录的指定路径。 In most cases using a relative file path is a bad idea, since running from a different directory will break the program. 在大多数情况下,使用相对文件路径是个坏主意,因为从其他目录运行会破坏程序。 It would be preferable to include the css file as resource. 最好将css文件作为资源包括在内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.