JavaFX Application Running in IntelliJ IDEA Struggles to Locate CSS File within Resources Directory

Concern Description:
While developing a JavaFX application using IntelliJ IDEA, I'm facing an issue where the application cannot find a CSS file placed in the resources folder.

In my project, there's a style.css file located under src/main/resources/view. However, when attempting to load it in my JavaFX application with

getClass().getResource("/view/style.css")
, it keeps returning null.

Code Implementation of Note:

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

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

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

Hurdles Encountered:

  1. Approach 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. Approach 2 (

    scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm());
    ):

    • Returns null, leading to an error upon calling .toExternalForm().

Additional Insights:

  • The project directory is accurately displayed, confirming the current working directory.

  • I have double-checked for any typographical errors in the file path.

  • The CSS file undeniably exists in the specified directory.

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

  • I am utilizing IntelliJ IDEA for my project setup, without Maven or Gradle. Here's the pertinent content from my .iml document:

    <?xml version="1.0" encoding="UTF-8"?gt;
    <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>
    

Query:

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

Your insights and suggestions are highly valued!

Efforts Made:

I have made numerous attempts to solve the persisting issue where getResource() continuously outputs null. Below are the steps I've taken:

  • Duplicated the problem in other classes within different packages, encountering the same dilemma of getResource() returning null.

  • Tried different strings to access the CSS file, such as:

    • "style.css"

    • "/style.css"

    • "view/style.css"

    • "/view/style.css"

  • Moved the CSS file directly to the resources folder.

  • Experimented with various CSS file names and creation methods.

  • Restarted IntelliJ IDEA.

  • Rebuilt the entire software.

  • Invalidated the cache in IntelliJ IDEA and restarted (I do this after every alteration just to make sure).

  • I did attempt replicating this in other classes of different packages. The getRecource() consistently returns null.

  • Added !?*.css to Settings -> Compiler -> Resource patterns.

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

  • Moved the resource folder directly into the project folder /src/main/resources -> /resources

Answer №1

I made a change in the Settings section by adding "!?*.css"" under Compiler -> Resource patterns.

However, it turns out that this was not the correct move.

By including .css files in the exclusion list, they are treated as NOT resources, which is actually counterproductive to what you want.

It seems that the compiler setting primarily applies to files within directories labeled as "Sources," and does not have an impact on files designated as "Resources." In my own experimentation, I observed that .css files located in directories marked as "Resources" were always copied to the output directory regardless of the Compiler | Resource patterns configuration. Therefore, this may not be the root cause of your problem.

Successful Experimentation

In order to test this further, I conducted the following steps:

Upon completion of these actions, the .css file placed in the designated resource folder was successfully copied to the build output directory and could be accessed using a getResource call as expected.

After building:

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

The resulting files included:

Main.class
styles.class

https://i.sstatic.net/SeLdZ.png

/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

The default configurations for a new Java project on IntelliJ IDEA 2023.2.4 (Ultimate Edition) remained unchanged:

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

Recommendation

Instead of manually configuring projects in the IDE, utilizing a build tool like Maven or Gradle, adhering to the Maven standard layout, and syncing the project build with your IDE tends to yield better results.

Answer №2

Gratitude for the valuable responses and assistance extended!

Upon careful evaluation of your feedback, it became evident that the issue did not lie within the code itself but rather in the project setup within IntelliJ. While pinpointing the exact cause within the setup proved challenging, I managed to find a resolution by approaching the problem differently.

The decision was made to reconstruct the project using Maven. A pivotal aspect of this process involved accurately configuring the VM arguments for JavaFX, which initially posed difficulties due to the distributed dependencies. Once these were appropriately set up, the application seamlessly recognized and loaded the CSS file.

The reconstruction of the project using Maven turned out to be the effective solution required. Appreciation to all for your contributions.

For those encountering similar issues and considering using Maven, here are my setup files:

  1. pom.xml

    <? xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>DDoc</groupId>
        <artifactId>SummerEase_Maven</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>21</maven.compiler.source>
            <maven.compiler.target>21</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <javafx.version>21.0.1</javafx.version> <!-- JavaFX version -->
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.30</version>
            </dependency>
            <!-- JavaFX dependencies -->
            <dependency>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-controls</artifactId>
                <version>21.0.1</version>
            </dependency>
            <dependency>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-fxml</artifactId>
                <version>21.0.1</version>
            </dependency>
            <dependency>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-graphics</artifactId>
                <version>21.0.1</version>
            </dependency>
            <dependency>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-media</artifactId>
                <version>21.0.1</version>
            </dependency>
            <dependency>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-web</artifactId>
                <version>21.0.1</version>
            </dependency>
            <dependency>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-swing</artifactId>
                <version>21.0.1</version>
            </dependency>
            <!-- Add other dependencies as needed -->
        </dependencies>
    
    </project>
    
  2. VM argument for running javafx

    --module-path
    /home/guillaume/.m2/repository/org/openjfx/javafx-base/21.0.1/:/home/guillaume/.m2/repository/org/openjfx/javafx-controls/21.0.1/:/home/guillaume/.m2/repository/org/openjfx/javafx-fxml/21.0.1/:/home/guillaume/.m2/repository/org/openjfx/javafx-graphics/21.0.1/
    --add-modules
    javafx.base,javafx.controls,javafx.fxml,javafx.graphics
    

    Make sure to include : between all your javafx folders to ensure correct jar selection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CodenameOne's innovative solution allows for the seamless conversion of a theme.res file into CSS format with ease

Thanks to the cn1-css library, Cascading Stylesheet Support for Codename One is made possible. I'm curious about whether there is a way to automatically convert a theme file (theme.res) into CSS code. And, if so, how are the images from the theme fil ...

Guide to creating an Android thread that can run continuously

Runnable updateSeekBar = new Runnable() { @Override public void run() { try{ while (true) { if (!isPlayerOff) { Log.d("Threads", "Thread running smoothly."); ...

Is it possible to conceal the dates from past months in the datepicker plugin?

Currently, I am utilizing a datepicker tool from jQuery UI and adjusting its CSS to suit my requirements. My goal now is to hide any dates that are not currently active, specifically those displayed from other months. I am unsure if this can be achieved ...

What is the method to retrieve the file path for the ImageIcon?

After creating an ImageIcon using the following code: ImageIcon ico =new ImageIcon("tree.png"); Is there a way to retrieve the path as a string? String path = ico.getPath(); ...

Ways to avoid a child element from overlapping another element

(I acknowledge that the question may sound a bit off, so please feel free to edit it if you can rephrase it better). So, I have this: jsFiddle As you can see, I'm attempting to recreate a basic Windows 7 aero effect (just for curiosity, fun, and lea ...

What is the process for establishing an access approach that enables the conversion of a string to a boolean value?

What is the process for creating an access method to convert a string into a boolean data type? See the example of a current access method below: protected boolean fullTime; /** * Retrieve the value of fullTime * * @return the value of fullTime */ pu ...

Adjusting the gridview headers to line up with a specific item and shifting the content of the item to the right

I am struggling with aligning the header and content in my gridview. I want the shirts to be underneath the header item, with the description moved to the left and the price 336 moved to the right. Something like this: https://i.sstatic.net/2i2IR.png Her ...

Creating a perfect design with Font Awesome 5 SVG icons and vertically aligned text at the top

Check out my code example on CodePen, view source. I'm looking for a way to align an icon and text vertically without using JavaScript. I want to maintain the li element's line-height and other styles. Any suggestions? ...

CSS sibling causing a shift in an absolutely positioned div

Check out this example http://jsfiddle.net/4cu8m/ <div id="main1"> <div id="inner1"</div> <div id="inner2"</div> </div> The positioning of inner1 and inner2 in the CSS are identical. They are both absolutely ...

Working with ArrayList: Efficiently using arraylist.set() method with multiple setters

I am currently working with 2 classes. The first one is my bot class: public class Bot { private int X; private int Y; private int degress; public int getX() { return X; } public int getY() { return Y; } ...

The alignment of h2 headings becomes disordered beyond a specific viewport width

Can someone help me with an issue I'm facing regarding the placement of my "rightside" navigation? The problem arises when the viewport width drops below 767px, causing the h2 elements in the rightnav to align themselves directly next to the #leftnav. ...

Verify the compatibility of POJOs in both directions using Jackson

In our system, Java POJOs are utilized as messages that travel through a message broker. Serialization and deserialization are performed using the Jackson JSON library. Each message (POJO) may exist in multiple versions: class UserCreatedV1 { private Strin ...

Choose the drop down selection in Selenium based on the variable that is provided as a string parameter

Context: Card stock - includes program details, stock location and country information Customer sell card screen - when selling a new card, the customer's address must be entered. Depending on the country inputted, certain fields (state/address line ...

The SessionFactory encountered a null pointer exception while trying to open a session

After spending several days working with Hibernate and MySQL, I encountered a NullPointerException error in my setUpSession.java file while running the program as a JUnit test. The error is related to the sessionFactory variable. My main objective at the ...

Simple Android: Displaying a user's text input

In my attempt to create an app where users can input their last name, first name, and address, I encountered a runtime error when trying to display the user inputs on a TextView. Upon clicking the submit button, instead of showing the user input, the Tex ...

What is the process for swapping the top row of a 2D matrix with the bottom row?

I am working with a 2-D array named A[4][7]: 1 8 4 6 9 8 7 1 1 1 9 8 8 5 1 1 1 0 1 1 1 1 1 1 1 1 1 1 Is there a way to swap the position of the first and last lines? Resulting in: 1 1 1 1 1 1 1 1 1 1 9 8 8 5 1 1 1 0 1 1 1 1 8 4 6 9 8 7 This needs to be ...

Unable to fetch JSON data in Android using Retrofit

Apologies for any language errors. I am currently learning about retrofit for Android development (previously used Volley), but I am facing issues. My class object PostsS private String userId; private String id; private String title; privat ...

Python Selenium error: NoSuchElementException - Unable to find the specified element

Coding Journey: With limited coding knowledge, I've attempted to learn through various resources without much success. Now, I'm taking a different approach by working on a project idea directly. The goal is to create a program that interacts wi ...

How to generate an array of objects in Java by implementing classes

I have been working on a project involving a text file that contains course information structured in a specific order: department, course number, and title. Despite my code compiling successfully, the first element of the array is defaulting to nothing wh ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...