4

伙计们,

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

在应用程序中,我为按钮使用了一些图像图标。按照 Internet 上的一些说明,我通过单击项目创建了一个“源”目录。我将源目录命名为“res”并将我的图像移动到该目录。


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文件的根目录中。以下调用有效:

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

我想知道是否有一些我忽略的步骤。

请注意,我不必对 pom.xml 为图像做任何特别的事情。Maven 自动拾取它们(除了将它们放在错误的位置)。

预先感谢您的帮助。

问候,彼得

4

3 回答 3

7

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

打包应用程序时应特别注意正确访问图像。例如,以下函数应该可以满足您的所有需求。

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图像目录中的文件。

如果ImageIcon需要,那么只需调用new ImageIcon(getImage("images/some-image.png"))就可以了。

于 2012-05-05T19:00:10.163 回答
0

看看maven资源插件

于 2012-05-05T18:39:35.127 回答
0

我的 favicon 位于 maven 项目的根目录中,但它没有包含在生成的战争中。通过大量谷歌搜索,我从 Maven 帮助页面获得了解决方案。

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
  <webResources>
    <resource>
        <directory>${project.basedir}</directory>
      <!-- the list has a default value of ** -->
      <includes>
        <include>favicon.ico</include>
      </includes>
    </resource>
  </webResources>
</configuration>
</plugin>
于 2017-03-28T07:14:09.147 回答