打包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
相关产品推荐
相关产品推荐

