简体   繁体   中英

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!!

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);

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.

我认为,答案可能是一个这些建议在这里

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM