Maven包装图像在jar文件的根目录下 [英] Maven packaging images in the root of the jar file

查看:268
本文介绍了Maven包装图像在jar文件的根目录下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Folks,

我正在使用Eclipse开发Java应用程序。 Maven用于创建最终的jar文件。

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

在应用程序中,我使用一些图标图标进行按钮。按照互联网上的一些说明,我通过点击项目创建了一个源目录。我将源目录命名为res,并将我的图像移动到此目录。

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

当应用程序未打包为jar文件(非常适合调试)。但是,当maven打包时,我看到图像被放在jar文件的根目录下。以下调用工作:

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.

注意我不需要为图像做任何特殊的pom.xml。 Maven自动接收它们(除了它们在错误的位置)。

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

提前感谢您的帮助。

问候,
Peter

Regards, Peter

推荐答案

如果您遵循标准的Maven项目目录结构,最好将所有非Java资源放在 src / main / resources 之下。例如,您可以创建一个子目录图像,以便完整路径为 src / main / resources / images 。此目录将包含所有应用程序映像。

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

此功能可用作 getImage(images /some-image.png)以便在图像目录中加载 some-image.png 文件。

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

如果 ImageIcon 是必需的,那么只需调用新的ImageIcon(getImage(images / some-image.png)) 会做的伎俩。

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

这篇关于Maven包装图像在jar文件的根目录下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆