You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

打包JAR文件后无法访问images目录图片的问题求助

打包JAR文件后无法访问images目录图片的问题求助

大家好,我最近写了一个Java Swing应用,用来加载本地images目录里的图片显示出来。本地直接编译运行完全没问题,但打包成JAR文件后就找不到图片了,一直报“Image not found.”的错误,想请各位帮忙分析下问题出在哪。

重现步骤

  • 直接编译运行(正常工作):
    javac Swing.java
    java Swing
    
  • 打包成JAR后运行(无法加载图片):
    javac Swing.java
    jar cfe Build.jar Swing .
    java -jar Build.jar
    

我的代码

import javax.swing.*;
import java.net.URL;

class Swing extends JFrame {
    private JLabel label = new JLabel();
    private JLabel image = new JLabel();
    static String[] myStrings = {"String1", "String2", "String3"};
    static String[] myImages = {"images\\image-1.jpg", "images\\image-2.jpg", "images\\image-3.jpg"};

    Swing() {
        super("Swing Test Application");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 700);
        setLayout(null);
        setLocationRelativeTo(null);
        
        label.setBounds(10, 0, 220, 100);
        add(label);
        image.setBounds(10, 200, 420, 420);
        add(image);
        
        setVisible(true);
    }

    void SetText(String strLabel, String imageFilename) {
        label.setText(strLabel);
        URL imageURL = getClass().getResource(imageFilename);
        if (imageURL != null) {
            ImageIcon imageIcon = new ImageIcon(imageURL);
            image.setIcon(imageIcon);
        } else {
            System.err.println("Image " + imageFilename + " not found.");
        }
    }

    public static void main(String arg[]) {
        Swing swing = new Swing();
        int i = 0;
        while (true) {
            swing.SetText(myStrings[i], myImages[i]);
            i++;
            if (i == 3) i = 0;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

现象说明

  • 直接运行java Swing时,images目录和Swing.class在同一目录下,图片能正常加载显示
  • 打包成JAR后,images目录和JAR文件放在同一位置,但运行JAR时就会输出“Image images\image-1.jpg not found.”这类错误

我自己猜测应该是资源路径的问题,因为代码里用了getClass().getResource()来加载图片,可能JAR文件里的资源路径处理方式和本地文件系统不一样?但具体怎么改实在没头绪,麻烦各位帮忙指点下~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:29:35