我在运行包含图像图标的可运行 jar 文件时遇到问题。
代码在 eclipse 上运行良好,并在 JFrame
中显示图标。我添加它的方法是将其添加到 JLabel
中,然后将该 JLabel
添加到 JFrame
中。我将项目导出到可运行的 Jar 文件中,然后双击该 jar。它不运行。
我测试了仅在没有图标代码的情况下将普通的 JLabel
添加到 JFrame
上,并且在导出并运行它时它可以工作。
每当我将以下行添加到代码中时,它都会弄乱可运行的 Jar 文件。
JLabel s1 = new JLabel(new ImageIcon(getClass().getResource("/Images/Pattern1.png")));
我注意到当它获取资源时可能会出现问题。我的 Image Pattern1 存储在名为 Images 的文件夹中,该文件夹位于我的项目 src 文件夹内。 因此,当我导出它时,我确信它位于可运行的 jar 文件中。
这是我的代码
package main;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame {
public MyFrame() {
JLabel s1 = new JLabel(new ImageIcon(getClass().getResource("/Images/Pattern1.png")));
this.add(s1);
//JLabel test = new JLabel("Test");
//this.add(test);
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
这就是我的项目中的文件的样子。
谢谢
最佳答案
特别是在 Windows 上,Java 对文件名中大小写的使用比较宽松。在 Eclipse 中运行时,Pattern1.PNG
可能是直接从文件系统中获取的。
然而,一旦嵌入到 Jar 中,大小写匹配就会变得精确。这是因为资源只是添加到 zip 文件中,Java 使用 Zip Entry 信息来查找内容。
确保您的命名准确以避免出现问题。尝试使用 /Images/Pattern1.PNG
而不是 /Images/Pattern1.png
关于java - 导出可运行 Jar 不适用于 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28575692/