0

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.

2
  • Any reason why you define twice -fx-background-color in 2 classes? Commented Jan 13, 2017 at 20:04
  • Sorry @NicolasFilotto. Please ignore that. I edited that out of the question. Thank you for pointing it out. Commented Jan 13, 2017 at 20:19

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.