Siva Subramaniam
Siva Subramaniam

Reputation: 124

Image not loading in jar file

I am trying to fix this problem. Trying different solutions but nothing works. I am using NetBeans IDE. I created a project with this structure and files:

E:\java\project\ecadpb\src\ecadpb

The image files are in

E:\java\project\ecadpb\src\

I have specified working folder for my project in Netbeans as E:\java\project\ecadpb

I have created my image icons like this

new ImageIcon("device21.png");

In my source file, it works perfectly while running the project in Netbeans but images are not showing up when I build and run my JAR file separately. But the image files are inside the JAR.

I have also tried the answers for the same question asked previously.

URL imageUrl=getClass().getResource("device21.png");
new ImageIcon(imageUrl);

But it doesn't work in my case. I am building a JAR file for the first time. Can anyone help me with this!!

Upvotes: 1

Views: 6220

Answers (4)

A-a-ron
A-a-ron

Reputation: 68

Create a source folder called Images (ie if you're using eclipse, right-click your project -> new ->sourceFolder). Call it whatever you want, i called my Images. Put some images in it.

Now i had JLabels where i gave them ImageIcons. Look at the following code.

    ImageIcon BPawn;
    ImageIcon WPawn;
    JLabel Label = new JLabel[8][8] //2D array of labels that gives each spot a position.
    public void setPieces(){
        //set up pawns in their respective positions.
        BPawn = new ImageIcon("Images/BPawn.png", "BPawn");
        WPawn = new ImageIcon("Images/WPawn.png", "WPawn");
    for(int i=0;i<Label[0].length;i++){
        Label[1][i].setIcon(BPawn);
        Label[6][i].setIcon(WPawn);
    }//end for

    }//end setPieces.

There is a lot more in setPieces() method, but this glimpse is how you would reference the images in your source folder when you create an executable jar and want the images to show up.

Upvotes: 1

Bitmap
Bitmap

Reputation: 12538

A simple way of doing this will be to add the image in your classpath or a directory in your classpath say img as shown below:

E:\java\project\ecadpb\src\main\java\img\device21.png 

And then load your image from this location like this:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("img/device21.png");
ImageIcon icon = new ImageIcon(resource);

Upvotes: 3

r0ast3d
r0ast3d

Reputation: 2637

I have used a similar approach,

a) Specify the package path to the image file name.

b) Make sure that the image file is not ommited by your build scripts and that it is present in your jar file.

Upvotes: 0

rk2010
rk2010

Reputation: 3529

I think answer could be one these suggestions here

Upvotes: 0

Related Questions