Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

java - Maven packaging images in the root of the jar file

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 buttons. Following some instructions on the Internet, I created a "source" directory by clicking on the project. I named the source directory as "res" and moved my images to this directory.


public static ImageIcon getIcon() {
  if (isThisJarfile()) {
     URL url = this.class.getResources("/res/myicon.png");
     return new ImageIcon(url);
  }else {
     return new ImageIcon("/res/myicon.png");
  }
}

This works fine when the app is not packaged as a jar file (great for debugging). However, when maven packages it, I see that the images are put in the root directory of the jar file. The following call works:

    URL url = this.class.getResource("/myicon.png");

I am wondering if there is some step that I overlooked.

Note that I didn't have to do anything special to pom.xml for the images. Maven automatically picked them up (except that it is putting them in the wrong location).

Thank you in advance for your help.

Regards, Peter

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...