Search code examples
javacssintellij-ideajavafx

JavaFX Application in IntelliJ IDEA Cannot Find CSS File in Resources


Issue Description:
I am developing a JavaFX application using IntelliJ IDEA and encountering an issue where the application does not locate a CSS file placed in the resources folder.

In my project, there's a style.css file located under src/main/resources/view. Despite this, when attempting to load it in my JavaFX application with getClass().getResource("/view/style.css"), it consistently returns null.

Relevant Code Implementation:

public class MainGui extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(new DocumentSelectionView());

        Scene scene = new Scene(borderPane, 1400, 900);

        // Attempting to load the CSS file
        scene.getStylesheets().clear();
        System.out.println(System.getProperty("user.dir")); // Prints the project directory

        // Different methods tried to add the stylesheet
        // Method 1
        scene.getStylesheets().add("src/main/resources/view/style.css"); 
        // Method 2
        scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm()); 
    }
}

Problems Encountered:

  1. Method 1 (scene.getStylesheets().add("src/main/resources/view/style.css");):

    • Results in the warning:
      WARNING: Resource "src/main/resources/view/style.css" not found.
  2. Method 2 (scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm());):

    • Returns null, leading to an error when attempting to call .toExternalForm().

Additional Information:

  • The project directory is correctly printed, confirming the working directory.

  • I have verified that there are no typographical errors in the file path.

  • The CSS file certainly exists in the specified directory.

  • The CSS file is not in the target output folder.

  • I am using IntelliJ IDEA for my project structure, not Maven or Gradle. Here is the relevant content from my .iml file:

    <?xml version="1.0" encoding="UTF-8"?>
    <module version="4">
      <component name="AdditionalModuleElements">
        <content url="file://$MODULE_DIR$" dumb="true">
          <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
          <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
          <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
          <excludeFolder url="file://$MODULE_DIR$/target" />
        </content>
      </component>
    </module>
    

Question:

What could be causing this failure to locate the style.css file, and how can I correctly load it into my JavaFX application?

Any insights or suggestions would be greatly appreciated!

Attempts:

I have attempted several approaches to resolve the issue where getResource() consistently returns null. Here's a summary of the steps I've taken:

  • Replicated the issue in other classes across different packages, encountering the same problem with getResource() returning null.

  • Tried various strings to locate the CSS file, including:

    • "style.css"

    • "/style.css"

    • "view/style.css"

    • "/view/style.css"

  • Moved the CSS file directly into the resources folder.

  • Experimented with different CSS file names and methods of creating these files.

  • Restarted IntelliJ IDEA.

  • Rebuilt the entire software.

  • Invalidated the cache in IntelliJ IDEA and performed a restart (I do this after every change just to be sure).

  • I did try replicating this in other classes of other packages. The getRecource() always returns null.

  • To Settings -> Compiler -> Resource patterns I've added !?*.css

  • getClass().getClassLoader().getResource("/view/style.css");

  • Moving the resource folder directly in the project folder /src/main/resources -> /resources


Solution

  • To Settings -> Compiler -> Resource patterns I've added !?*.css"

    You don't want to do that.

    That treats .css files as NOT resources. That is the opposite of what you want.

    Note though that (I think) the compiler setting is just for handling files under directories marked as Sources, and won't affect files that are marked as Resources. From my tests, .css files under directories I marked a Resources were always copied to the output directory, regardless of the Compiler | Resource patterns setting. So it likely isn't the root cause of your issue.

    Working example

    I tried:

    • creating a new Java project (not JavaFX project) in Idea with generated sample code (using the Idea new Java project wizard).
    • manually setting a resource path in the IDE for the module.
    • Placing a css resource file in the resource directory I configured.
    • Modified sample java code in the src directory to lookup the resource.

    By default (with no other change) it the .css file I put in the resource directory I created was copied to the build output directory and could be found by a getResource lookup as expected.

    After building:

    <projectdir>/out/production/<modulename>/
    

    Contained these files:

    Main.class
    styles.class
    

    resources

    /src/Main.java

    public class Main {
        public static void main(String[] args) {
            System.out.println("Hello world!");
            System.out.println(Main.class.getResource("/styles.css"));
        }
    }
    

    /resources/styles.css

    .root {
        -fx-base: mistyrose;
    }
    

    Output

    Hello world!
    file:/C:/dev/resourcetest/out/production/resourcetest/styles.css
    

    Settings | Compile | Resource patterns

    These are defaults for a new Java project with Idea 2023.2.4 (UE), I didn't change them:

    !?*.java
    !?*.form
    !?*.class
    !?*.groovy
    !?*.scala
    !?*.flex
    !?*.kt
    !?*.clj
    !?*.aj
    

    Recommendation

    Using a build tool (e.g. Maven or Gradle), following the Maven standard layout, and synching the build project with your IDE is usually a better approach than manually configuring the project in the IDE.