#ImageIcon returns null when loading image from resources folder in VS Code project

3 messages · Page 1 of 1 (latest)

feral belfry
#

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!

potent mauveBOT
#

This post has been reserved for your question.

Hey @feral belfry! Please use /close or the Close Post button 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.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.