DatForis
DatForis

Reputation: 197

where do i put images for icons in java (netbeans) and how do i link them to the code?

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

Answers (5)

Joop Eggen
Joop Eggen

Reputation: 109557

As you asked for conventions: using the Maven build infrastructure, you would have

  • src/main/java - java packages
  • src/main/resources - resources like your images
  • src/main/resources/images/Flag.png - some resource (no convention)

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

Petr.M
Petr.M

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

Nisheeth Shah
Nisheeth Shah

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

Kushal Shukla
Kushal Shukla

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

Riduidel
Riduidel

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

Related Questions