JAR文件外的图像?

时间:2015-03-07 14:51:38

标签: java image swing embedded-resource

我真的很困惑......所以我的文件结构是这样的

 /PCBuilder
   -PCBuilder.jar <= The main program
   /PCBuilder/Images
      /accessories/*.png files here
      /gui/*.png files here
      /parts/*.png files here
      /prebuild/*.png files here

我的代码

 private void okMouseEntered(java.awt.event.MouseEvent evt) {                                
    ok.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PCBuilder/images/gui/Okay_glow.png")));
}                               

private void okMouseExited(java.awt.event.MouseEvent evt) {                               
    ok.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PCBuilder/images/gui/Okay_red.png")));
} 

当我在Netbeans上运行它时,它工作正常......但是当我尝试编译它并运行JAR文件时,它显示了这个错误......

 D:\Documents\NetBeansProjects\PCBuilder_GUIHACKED\dist>java -jar PCBuilder_GUIHACKED.jar
 Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
 at javax.swing.ImageIcon.<init>(Unknown Source)
 at PCBuilder.welcomescreen.okMouseEntered(welcomescreen.java:87)
 at PCBuilder.welcomescreen.access$100(welcomescreen.java:12)
 at PCBuilder.welcomescreen$1.mouseEntered(welcomescreen.java:45)
 at java.awt.Component.processMouseEvent(Unknown Source)
 at javax.swing.JComponent.processMouseEvent(Unknown Source)
 at java.awt.Component.processEvent(Unknown Source)
 at java.awt.Container.processEvent(Unknown Source)
 at java.awt.Component.dispatchEventImpl(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)

任何想法如何解决这个问题?感谢

1 个答案:

答案 0 :(得分:1)

您的图片位于可执行jar文件的父目录中,因此最好获取父路径,然后从目录中读取图像:

作为解决方案:

File f = new File(this.getClass().getProtectionDomain().
                        getCodeSource().getLocation().toURI().getPath());
String path = f.getParent() + "/images/print.png";
lbl1.setIcon(new ImageIcon(path));

1.获取jar文件路径:

File f = new File(this.getClass().getProtectionDomain().
                        getCodeSource().getLocation().toURI().getPath());

2.获取图像的绝对路径(例如{jar_file_parent_directory} /images/print.png):

String path = f.getParent() + "/images/print.png";

3.设置组件的图标(例如JLabel lbl1)

lbl1.setIcon(new ImageIcon(path));