AhasVerus
AhasVerus

Reputation: 31

eclipse JavaFX css resource not found

I'm having a problem with stylesheets for JavaFX GUI. My stylesheet won't load and I get this error:

com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
WARNING: Resource "file:images\stylesheet.css" not found.

I tried putting the stylesheet.css in the same folder as the images. The images are no problem, but the stylesheet is not found.

scene.getStylesheets().add("images\\stylesheet.css");

I also tried this:

scene.getStylesheets().add("file:images\\stylesheet.css");

and:

scene.getStylesheets().add("file:///images/stylesheet.css");

I also tried different folders, like the one where the .java file is in.

Nothing seems to work. It's like Eclipse doesn't recognise stylesheets.

Upvotes: 1

Views: 4645

Answers (4)

Martin Bubel
Martin Bubel

Reputation: 11

I am using pretty much the same solution as by the previous answer, except for one extension, the toString() call:

scene.getStylesheets().add(getClass().getResource("cssfile.css").toString());

In case the file that calls the above command is NOT in the same pacakge/directory as the css-file, add a relative path, i.e. "images/cssfile.css".

Upvotes: 1

Grumblesaurus
Grumblesaurus

Reputation: 3119

The issue is that java's com.sun.javafx.css.StyleManager works with URLs, but it doesn't do a great job of converting File.toString() to a url, so you have to pass it a String that has already been converted to a file, to a URL, and back to a String. So when it parses the string as a URL, it doesn't choke on the space character.

This works:

String fontSheet = fileToStylesheetString( new File ("location") );

if ( fontSheet == null ) {
    //Do Whatever you want with logging/errors/etc.
} else {
    scene.getStylesheets().add( fontSheet );
}

public String fileToStylesheetString ( File stylesheetFile ) {
    try {
        return stylesheetFile.toURI().toURL().toString();
    } catch ( MalformedURLException e ) {
        return null;
    }
}

Upvotes: 4

ItachiUchiha
ItachiUchiha

Reputation: 36722

Images in JavaFX internally implement the loading of resources from the class loader, but unfortunately this is not true for the stylesheets. So if you say :

new Image("/Images/background.png");

it gets transformed to :

new Image(getClass().getClassLoader().getResource("Images/background.png");

but it doesn't happen in the case of getStylesheets().add(). So in order to run it you need to add a classloader yourself :

scene.getStylesheets().add(
      getClass().getClassLoader().getResource("images\\stylesheet.css"));

Note: The path here depends on the location of the css file.

Upvotes: 0

ttarczynski
ttarczynski

Reputation: 1014

Try with getClass().getResource("/images/stylesheet.css");

scene.getStylesheets().add(
  getClass().getResource("/images/stylesheet.css")
);

Upvotes: 0

Related Questions