Reputation: 1614
I'm not working in any development environment like Eclipse or NetBeans. I work from the Windows Terminal. My root folder is Project, containing src, res, bin.
res contains -png files that i want to use in the java classes in the src folder. Now I'm confused because manually ordering the structure of the files and folders in my Project have no influence on how my code behaves. I still need to declare what package a class lies in in the code. I can't declare (in code) that Image1.png lies in the package res. How do my classes then find this image?
I have tried putting the image in the same package as the class that wants access and simply trying getResource("Image1.png")
but no: NullPointerException.
Nobody seems to have this problem and I can't find answers anywhere.
the layout of my project:
Project
bin
samplecode
SampleCodeClass1.class
SampleCodeClass2.class
res
Image1.png
src
samplecode
SampleCodeClass1.java
SampleCodeClass2.java
now when I open a Terminal from the Project directory and enter:
java -cp bin;res samplecode.SampleCodeClass1
i get at javax.swing.ImageIcon.<init>(Unknown Source)
referring to this line in my code:
ImageIcon ii = new ImageIcon(this.getClass().getResource("Image1.png"));
Upvotes: 0
Views: 209
Reputation: 691665
You have to understand that the classpath that matters is the one used at runtime. Not when compiling the Java source files. If the structure is
bin
com
foo
MyClass.class
res
com
foo
Image1.png
then you'll be able to use MyClass.class.getResource("Image1.png")
or AnyClassInAnyPackage.class.getResource("/com/foo/Image1.png")
, provided that the res
folder is in the runtime classpath:
java -cp bin;res com.foo.MyClass
If the res
folder is not in the classpath, then it can't be loaded by the ClassLoader.
EDIT:
The image is in the default package. The class is in the package samplecode. So they're not in the same package. So you can't use this.getClass().getResource("Image1.png")
, which would look for the image in the same package as the class. Instead, you must use the full path of the image from the root of the classpath, starting with a /
: this.getClass().getResource("/Image1.png")
Upvotes: 2
Reputation: 3767
What API are you referencing getResource
from? java.util.ResourceBundle
? Make sure the files are referencing the path you put them in, relative to the classpath. This also requires that you specify the runtime classpath (e.g. java -classpath
) appropriately.
Upvotes: 0