Setting imageIcon without full path

1.2k views Asked by At

I'm trying to st the icon on a Jlabel but I get "NullPointerException" every time I run it. It does run while I put in the full path but I don't want to do that because I want to move the java programme around the environment.

jLabel1.setIcon(new ImageIcon(this.getClass().getResource("/data/images/image.jpg")));

I believe the problem is in the path I'm trying to use.

My rough project environment is:

projectfolder/src
projectfolder/data/images/image.jpg

I've tried using:

/image.jpg
/data/images/image.jpg
data/images/image.jpg
.\\data\\images\\image.jpg

What am I doing wrong?

1

There are 1 answers

1
J. TenniƩ On BEST ANSWER

Class#getResource() returns the resource relative to your class' location. Use ClassLoader#getResource() instead. If using the default class loader, it returns the resource relative to the classpath of your program.

this.getClass().getClassLoader().getResource("data/images/image.jpg")

You should place your data folder inside the src folder. Otherwise the data folder is not contained in the program's .jar.