Reputation: 197
I'm trying to make a Jframe class that has buttons with icons
public ImageIcon Flag = new ImageIcon(getClass().getResource("resources/Flag.png"));
Gives me a null pointer exception
"C:\Users\Khalidi\Documents\NetBeansProjects\MineSweeper\resources\Flag.png"
Is the full directory to reach the image I want I created the folder resources to house the images I need Where should i place the images? And what line of code should i be writing?
Thanks in advance
Upvotes: 2
Views: 7284
Reputation: 109557
As you asked for conventions: using the Maven build infrastructure, you would have
In your created jar / .classes
/images/Flag.png
public ImageIcon Flag = new ImageIcon(getClass().getResource("/images/Flag.png"));
Here, Class.getResource()
uses a relative path to the package of the class; therefore, using an absolute path as above ("/...") is easiest.
Upvotes: 3
Reputation: 136
You can simply place a folder resources to the folder with compiled classes and make ImageIcon like this.
public ImageIcon Flag = new ImageIcon("resources/Flag.png");
Upvotes: 1
Reputation: 608
Try using the package path with the same method. for example, if my image is in org.nisheeth.resources package, it should be written as follows.
public ImageIcon flag = new ImageIcon(Test.class.getResource("/org/nisheeth/resource/Flag.png"));
Upvotes: 4
Reputation: 110
Create a package say ImgPack and paste all your images to this package and access all the images using
ImageIcon ii = new ImageIcon(System.getProperty("user.dir")+"\\src\\ImgPack\\<Imagename.extention>");
Upvotes: -1
Reputation: 22292
When you're loading your images using getClass().getResource()
, the JVM in fact uses your CLASSPATH to load the resource (you should take a close look at Class#getResource(...)
).
As a consequence, to have your resource available, you must push it to your project output folder (must be something like target
, no ?).
Upvotes: 3