问题
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