Jar Embedded Resources NullPointerException

我最初是从Chillax开始的,在遇到如此多的问题接近截止日期之后,我回到了IDE我更熟悉的IDE,NetBeans,我将我的方法改为更基本的“小行星”型游戏:

  • NBs zip文件: http ://ge.tt/4T5tBFT/v/0?c
  • text:git clone git://gist.github.com/4248746.git
  • 嵌入?:

在NetBeans中,我得到:

Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.(ImageIcon.java:205) at gayme.Craft.(Craft.java:27) at gayme.Board.(Board.java:54) at gayme.Gayme.(Gayme.java:9) at gayme.Gayme.main(Gayme.java:19) Java Result: 1 

消息来源:(工艺26-34)

  public Craft() { ImageIcon ii = new ImageIcon(this.getClass().getResource("craft.png")); image = ii.getImage(); width = image.getWidth(null); height = image.getHeight(null); missiles = new ArrayList(); visible = true; x = 40; y = 60;} 

(理事会54)

  craft = new Craft(); 

(Gayme 9)

  add(new Board()); 

(Gayme 19)

  new Gayme(); 

我有一些问题,我真的需要解决,而我的睡眠不足的大脑每个人都会亏损。 随意帮助您选择相应的游戏。 非常感谢你们!

有3种方法:

  • Class#getResourceAsStream(String name)
  • Class#getResource(String name)
  • ToolKit #createImage(URL url)

关于使用Jar文件和资源的一些事项要记住:

  • JVM区分大小写,因此文件和包名称区分大小写。 即主类位于mypackage中,我们现在无法使用以下路径提取它: myPackAge

  • 任何时期’。’ 位于包名称内的应该用’/’代替

  • 如果名称以’/’(’\ u002f’)开头,则资源的绝对名称是’/’后面的名称部分。 资源名称以/开始执行类时开始,资源位于不同的包中。

让我们使用我首选的getResource(..)方法将它放到测试中,它将返回我们资源的URL:

我创建了一个包含2个包的项目: org.testmy.resources

在此处输入图像描述

正如您所看到的,我的图像位于my.resources中,而包含main(..)的Main类位于org.test中

Main.java:

 import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Main { public static final String RES_PATH = "/my/resources";//as you can see we add / to the begining of the name and replace all periods with / public static final String FILENAME = "Test.jpg";//the case sensitive file name /* * This is our method which will use getResource to extarct a BufferedImage */ public BufferedImage extractImageWithResource(String name) throws Exception { BufferedImage img = ImageIO.read(this.getClass().getResource(name)); if (img == null) { throw new Exception("Input==null"); } else { return img; } } public static void main(String[] args) { try { BufferedImage img = new Main().extractImageWithResource(RES_PATH + "/" + FILENAME); } catch (Exception ex) { ex.printStackTrace(); } } } 

如果您在RES_PATH实际文件进行适当更改的情况下使用RES_PATHFILENAME的名称,您将获得exception(只显示我们对路径的谨慎程度)

更新:

对于您的具体问题,您有:

 ImageIcon ii = new ImageIcon(this.getClass().getResource("craft.png")); 

它应该是:

 ImageIcon ii = new ImageIcon(this.getClass().getResource("/resources/craft.png")); 

Alien和其他class级也需要改变。