Maven packaging images in the root of the jar file

后端 未结 3 1856
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 09:24

Folks,

I am developing a Java application using Eclipse. Maven is used to create the final jar file.

In the application, I use some image icons for the butto

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 09:48

    If you're following the standard Maven project directory structure then it is best to put all non-Java resources under src/main/resources. For example, you could create a subdirectory images, so that the full path would be src/main/resources/images. This directory would contain all your application images.

    A special care should be taken to properly access images when application is packaged. For example, the following function should do everything you need.

    public static Image getImage(final String pathAndFileName) {
        final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
        return Toolkit.getDefaultToolkit().getImage(url);
    }
    

    This function can be used as getImage("images/some-image.png") in order to load some-image.png file in the image directory.

    If ImageIcon is required then simply calling new ImageIcon(getImage("images/some-image.png")) would do the trick.

提交回复
热议问题