简体   繁体   中英

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.

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;
    }
}

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, ie "images/cssfile.css" .

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM