Search code examples
javaurlresourcesimageicon

Java: Cannot access images in resources


I've been trying to export my project as a Runnable Jar, but my resources would not load because I was directly trying to access the image from my project's path. For example:

ImageIcon icon = new ImageIcon("resources/icon.png");

This would work when I ran the project from Eclipse itself, but I noticed that the images were not being included in the jar file. So after researching, I found out that I need to create source folders and put the images/text files inside them, and then use getClass().getResource() in order to access them. However, when I do this, the URL is always returned as null.

For reference, this is what my project explorer looks like:

Test
---src

---resources
   ---icon.png

---config
   ---file.ini

And here is the code that is giving me a NullPointerException when trying to access icon.png:

ImageIcon icon = getClass().getResource("/resources/icon.png");

Alternatively, I have also tried:

ImageIcon icon = getClass().getClassLoader().getResource("resources/icon.png");

But that also ends up in a NullPointerException. I have checked many solutions online but none of them have seemed to work for me. Please note that I also need to be able to access the .ini file, so a solution that only works for images won't fully solve my problem. Any help would be greatly appreciated, thanks.


Solution

  • Your structure needs to be:

    TEST
       -SRC
         -Resources
           -icon.png
    

    The way your code is right now is there is no image because your code is referencing /src/resources not test/resources