ImageIcon returns null when loading image from resources folder in VS Code project
I'm building a GUI for a Java trivia game using JPanel components. I have an image named gaming.png that I’m trying to load using the following line in my MusicTriviaGameMessagePanel.java
private static final String IMAGE_FILENAME = "trivia/resources/images/gaming.png";
ImageIcon imageIcon = new ImageIcon(getClass().getResource(IMAGE_FILENAME));
However, when I run the program using the terminal with:
java -cp bin trivia.view.MusicTriviaGameMainPanel
I get the following error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
This tells me that the image path is being resolved as null. Here's what I’ve done so far:
My directory structure is:
/trivia
├── view/
├── resources/
└── images/
└── gaming.png
I compiled my .java files into the bin/ folder with:
javac -d bin $(find trivia -name "*.java")
Then I copied the resources folder into bin/:
cp -R trivia/resources bin/trivia
I verified that bin/trivia/resources/images/gaming.png does exist.
I also removed the leading / from the image path string, which I read was necessary when using getClass().getResource(...).
Why is getClass().getResource("trivia/resources/images/gaming.png") still returning null? Am I placing the image in the wrong location or missing something about how resources are resolved in this case?
Thanks in advance!



1 Reply
⌛ This post has been reserved for your question.
Hey @Chuchi! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.