ImageIcon lost after creating a runnable JAR file

耗尽温柔 提交于 2019-12-12 03:44:29

问题


The project runs fine when I click play in Eclipse but after I created the runnable JAR file, The ImageIcon for the button is gone.
The images are stored within the src folder, uder a subfolder images.
I created the image icon as

  • Icon playIcon = (Icon) new ImageIcon("src/images/play.png");
  • Although I am using a relative path, the button does not display images, How do I get the images even in the JAR file?



    Update after Nikolay Kuznetsov's answer

    I ended up creating a very unstructured monolithic code for screen recorder and now it is slightly difficult to implement what he said.
    I was wondering if there is a way like creating a class or interface that will contain all these resources.

  • For example:
  • public class embeddedResources {
        public static Icon blackCursor;
        public static Icon whiteCursor;
        ...
        ...
    }  
    

    Then all I have to do is import these statics and in my main ScreenRecorder class,

    this.blackCursor = embeddedResources.blackCorsor;
    

    回答1:


    I am using this method to read image into BufferedImage where IconManager is class where it is defined.

    private static BufferedImage readBufferedImage (String imagePath) {
        try {
            InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
            BufferedImage bimage = ImageIO.read(is);
            is.close();
            return bimage;
        } catch (Exception e) {
            return null;
        }
    }
    



    回答2:


    I had the same problem. Try to make you JAR file and add your images to an extern folder. So you have a folder "Game" in this folder are the folder for your images called "images" or so and your jar file. If you now edit you folder path to "../images/play.png" it should work.



    来源:https://stackoverflow.com/questions/14023146/imageicon-lost-after-creating-a-runnable-jar-file

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