How to add css to a JavaFx element

好久不见. 提交于 2019-12-25 05:47:08

问题


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");

That doesn't get picked up.

What could I be doing wrong?

Thank you in advance.


回答1:


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());

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.



来源:https://stackoverflow.com/questions/41642403/how-to-add-css-to-a-javafx-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!