3

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;
}
8
  • Check the contents of the build folder to see if the CSS file is in the expected place. Commented Jan 20, 2017 at 18:43
  • this refer to what here ? Commented Jan 20, 2017 at 18:55
  • @James_D the .css file got copied by eclipse in bin/CSS/application-container.css, so it seems that's okay. Don't know why there is no resources folder inside bin though Commented Jan 20, 2017 at 19:00
  • @BoHalim this in this context refers to a BorderPane Commented Jan 20, 2017 at 19:01
  • There's no resources folder inside bin, because it's a source folder, not a package. That all looks correct. Are you certain that getClass().getResource("/CSS/application-container.css") is returning null? (i.e. you're not getting the npe from somewhere else). Try System.out.println(getClass().getResource(...)) to check. Commented Jan 20, 2017 at 19:05

1 Answer 1

1

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