有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);

共 (2) 个答案

  1. # 1 楼答案

    看起来您在path的末尾缺少了一个“/”。这样做:

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

    关键是首先为包含目录创建一个文件,然后使用构造函数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")));
    }
    
    // ...
    
  2. # 2 楼答案

    诊断这个问题最简单的方法是像下面这样应用简单的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。尝试并分享结果