java使用与已编译Jar相同文件夹中的图像不工作
我所要做的就是使用一个图像创建一个JLabel,该图像与。jar,如果它不存在,它将加载位于。你自己。图片存在于文件夹中,但它始终默认为文件夹中的图片。罐子
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File logo = new File(path + "logo.png");
JLabel lblNewLabel_1;
if (logo.exists()){
lblNewLabel_1 = new JLabel(new ImageIcon(logo.getPath()));
} else {
lblNewLabel_1 = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/Coffee.png")));
}
frame.getContentPane().add(lblNewLabel_1, BorderLayout.WEST);
final JLabel lblStatus = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/status1.png")));
frame.getContentPane().add(lblStatus, BorderLayout.EAST);
# 1 楼答案
看起来您在
path
的末尾缺少了一个“/”。这样做:关键是首先为包含目录创建一个文件,然后使用构造函数
File(File dir, String name)
而不是字符串连接此外,您应该提前检查文件夹和文件权限,为错误诊断提供适当的日志输出。为此,请使用
canRead()
而不是exists()
(假设log
可用作某些日志记录工具-替换为您选择的日志记录机制):# 2 楼答案
诊断这个问题最简单的方法是像下面这样应用简单的
System.out.println()
检查结果,并根据需要调整连接路径。我猜这条路径要么指向与您想象的不同的目录,要么就是在末尾缺少一个
File.separator
。尝试并分享结果