Search code examples
csseclipsejavafxnullpointerexceptiongetresource

JavaFX loading CSS style from resources folder


Project Structure:

Project Structure

I'm currently developing a JavaFX application in Eclipse and I'm having trouble loading a .css stylesheet from the resources folder.

I've already added the resources folder to the classpath (Project Properties -> Source -> Add Folder)

The following code is being used:

this.getStylesheets().add(getClass().getResource("/CSS/application-container.css").toExternalForm());

getResource() is throwing NullPointerException I've read other posts and tried everything but can't seem to get it to work.

EDIT: Managed to get it working by deleting and restoring the bin folder. Now the .css is loaded but by some reason it's not being applied, however using the javaFX method .setStyle(...) with the same content of the .css, it works.

private void buildHeader() {
    this.header.setId("header-container");
    this.getStylesheets().add(getClass().getResource("/CSS/application-container.css").toExternalForm());
    // this.header.setStyle("-fx-background-color: #7b9bce;");      this way works
}

CSS:

@charset"utf-8";

#header-container {
    -fx-background-color: #7b9bce;
}

Solution

  • Finally got it working with the external .css, apparently JavaFX CSS parser doesn't allow @charset "utf-8" or any @ anotation. It didn't show any warning whatsoever.

    Solution:

    Change this:

    @charset"utf-8";
    
    #header-container {
        -fx-background-color: #7b9bce;
    }
    

    To this:

    #header-container {
        -fx-background-color: #7b9bce;