Picture inside .jar file wont work when I export it

馋奶兔 提交于 2019-12-25 04:27:51

问题


Picture inside .jar file wont work when I export it.

I made a Java program that displays a picture, and it works perfectly in Eclipse, but when I export it to a .jar file, it wont display the picture. I just started learning Java, and I have no experience with creating Jar files and using files from inside the jar file.

Heres my code:

import javax.swing.*;
class displayPicture{
public static void main(String args[]){


    JFrame frame = new JFrame();
    ImageIcon icon = new ImageIcon("src/img.gif");
    JLabel label = new JLabel(icon);

    //Create the frame
    frame.add(label);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}
}

It shows the picture when I run it in Eclipse, but when I export it to a .jar file, it just shows a blank window.


回答1:


Two things...

First

The path src is unlikely to exist once the code is build

Second

ImageIcon(String) assumes the String reference is a reference to a file on the file system. Resources stored within the context of the application are not files and are treated differently. They are commonly known as embedded resources.

Instead, try using ImageIcon icon = new ImageIcon(displayPicture.class.getResource("img.gif")); or ImageIcon icon = new ImageIcon(displayPicture.class.getResource("/img.gif"));

I prefer to use ImageIO.read as it throws an IOException when something goes wrong and supports more file formats.

See Reading/Loading an Image for more details.

You should also take the time to have a read through Code Conventions for the Java Programming Language and Initial Threads



来源:https://stackoverflow.com/questions/22468906/picture-inside-jar-file-wont-work-when-i-export-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!