Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将css添加到JavaFx元素_Java_Css_Javafx - Fatal编程技术网

如何将css添加到JavaFx元素

如何将css添加到JavaFx元素,java,css,javafx,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:

我正在尝试将外部.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
。而是使用
文件
类的内置方法:

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

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

不要尝试将文件名转换为
URL
您自己。而是使用
文件
类的内置方法:

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

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

有什么理由在两个类中定义两次
-fx背景色
?抱歉@NicolasFilotto。请忽略这一点。我把它删掉了。感谢您指出。您为什么要在两个类中定义两次
-fx背景色
?抱歉@NicolasFilotto。请忽略这一点。我把它删掉了。谢谢你指出这一点。