使用与编译的Jar相同的文件夹中的图像不起作用

时间:2015-09-10 22:23:56

标签: java swing

我要做的就是使用与.jar位于同一目录中的图像创建一个JLabel,如果它不存在,它将加载位于.jar iteself内的默认照片。图片存在于文件夹中,但它始终默认为.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);

2 个答案:

答案 0 :(得分:0)

诊断此问题的最简单方法是在此处应用简单的System.out.println()

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(;
System.our.println("Jar path is "+path); <- you will see the actual path content here
File logo = new File(path + "logo.png");

检查结果并根据需要调整连接路径。我想这条路径要么指向不同的目录而不是你想象的那样,要么就是最后错过了File.separator。试试并分享结果!

答案 1 :(得分:0)

看起来你在path的末尾错过了一个'/'。这样做:

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File logo = new File(new File(path).getParentFile(), "logo.png");
...

要抓住的是首先为包含目录创建一个File,然后使用构造函数File(File dir, String name)而不是字符串连接。

此外,您应该提前检查文件夹和文件权限,为错误诊断提供正确的日志记录输出。为此,请使用canRead()而不是exists()(假设log可用作某些日志记录工具 - 替换为您选择的日志记录机制):

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File sourceLocation = new File(path);

// go up in the hierarchy until there is a directory
while (sourceLocation != null && !sourceLocation.isDirectory()) {
    sourceLocation = sourceLocation.getParentFile();
    if (sourceLocation == null) {
        log.warn(path + " is not a directory but has no parent");
    }
}

if (sourceLocation != null && sourceLocation.canRead()) {
    File logo = new File(sourceLocation, "logo.png");
    if (logo.canRead()) {
        log.info("Using logo " + logo.getAbsolutePath());
        lblNewLabel_1 = new JLabel(new ImageIcon(logo.getPath()));
    } else {
        log.warn("can not read " + logo.getAbsolutePath());
    }
}

if (lblNewLabel_1 == null) {
    log.warn("logo location not accessible, using default logo: " + sourceLocation);
    lblNewLabel_1 = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/Coffee.png")));
}

// ...