tomaswandahl
tomaswandahl

Reputation: 54

How do I get JavaFX-CSS to work?

So, I am having trouble getting CSS-styling to work in my JavaFX-project.

I have added an external stylesheet with:

scene.getStylesheets().add("Style.css");

... which links to the file Style.css in the same folder:

.root{
    -fx-background-color: #000000;
}

.button {
    -fx-background-color: #AB4642;
}

However, no changes occur when I run the program. The buttons stay the same, and the background stays the same. I have tried assigning unique classes to button and styling them that way, but that doesn't help.

How do I get the styling to actually work? How do I add an external CSS-file to the JavaFX-project?

Upvotes: 0

Views: 543

Answers (1)

James_D
James_D

Reputation: 209299

From the documentation for getStylesheets()

The URL is a hierarchical URI of the form [scheme:][//authority][path]. If the URL does not have a [scheme:] component, the URL is considered to be the [path] component only. Any leading '/' character of the [path] is ignored and the [path] is treated as a path relative to the root of the application's classpath.

So

scene.getStylesheets().add("Style.css");

will look for Style.css in the root of the classpath, not relative to the current class.

If you want to search relative to the current class, get the URL from getClass().getResource(...) and call toExternalForm() to convert to a string:

URL stylesheetURL = getClass().getResource("Style.css");
scene.getStylesheets().add(stylesheetURL.toExternalForm());

Alternatively, just specify the complete path, e.g. if the stylesheet is in the package com.mycompany.myproject, then do

scene.getStylesheets().add("com/mycompany/myproject/Style.css");

Upvotes: 2

Related Questions