如何将css添加到JavaFx元素 [英] How to add css to a JavaFx element
问题描述
我试图在Java FX场景图中添加外部 .css 文件,如下所示:
I'm trying to add a an external .css file to a Java FX scene graph as follows:
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;
}
样式类添加得很好,除非我尝试添加自定义类到元素:
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");
不会被接受。
我可以做什么错误?
提前谢谢。
推荐答案
不要尝试将文件名转换为 URL
自己。而是使用 File
类的构建方法:
Don't try to convert the file name to a URL
yourself. Instead use the build in methods of the File
class:
scene.getStylesheets().setAll(f.toURI().toURL().toExternalForm());
这假定文件位于当应用程序运行时相对于当前工作目录的指定路径。在大多数情况下,使用相对文件路径是一个坏主意,因为从不同的目录运行将打破程序。最好是将css文件作为资源。
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添加到JavaFx元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!