问题描述
我看到这个问题已经被问过很多次了,但我没有找到任何适合我的解决方案。
我正在尝试加载图像并将其显示在 jdialog 上。这在我从 Eclipse 运行应用程序时有效,但是当我生成可执行 JAR(使用 Maven)并运行 JAR 时,jdialog 出现而没有任何图像。
我把所有的类都放在/src/main/java 中,而我的图像在/src/main/resources 中。解压Maven生成的JAR,就可以找到我的镜像了,估计不是Maven的问题。
这是我用来加载图像的代码(我在这里找到它:Eclipse exported Runnable JAR not showing images):
URL url = myclass.class.getResource("/pic.gif");
ImageIcon icon = new ImageIcon(url);
如果有帮助,那就是类的全部代码:
public class LoadingWindow {
private jdialog dialog;
public LoadingWindow() {
this.dialog = new jdialog();
this.dialog.setDefaultCloSEOperation(jdialog.disPOSE_ON_CLOSE);
this.dialog.setTitle("Veuillez patienter");
this.dialog.setSize(300,200);
URL url = LoadingWindow.class.getResource("/wait.gif");
ImageIcon icon = new ImageIcon(url);
JLabel imageLabel = new JLabel();
imageLabel.setIcon(icon);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
this.dialog.getContentPane().add(imageLabel);
this.dialog.setLocationRelativeto(null);
this.dialog.setVisible(true);
}
}
谢谢!
解决方法
你的 jar 是一个可执行的 jar 吗?通过 maven 生成的 jar 称为瘦 jar,而不是可执行 jar。当你想通过 jar 运行你的应用程序时,它必须是一个可执行的 jar。如果它不是可执行的 jar,那么将下面的插件添加到你的 pom.xml 并构建项目。在您的目标文件夹中,将生成 2 个 jar。使用“jar-with-dependencies.jar”。
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass><Your fully qualified main class name></mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
,
如果它可以帮助任何人,这个解决方案对我有用:
我在 /src/main/resources(称为图像)中创建了一个新存储库,我将图像放在其中。
然后,我只是以这种方式加载图像:
URL url = LoadingWindow.class.getResource("/DirInResources/YourPic.png");
ImageIcon icon = new ImageIcon(url);