繁体   English   中英

将 URL 解析为 ImageIcon 时出现 NullPointerException

[英]NullPointerException when parsing URL to ImageIcon

我正在关注一些关于 JMonkey2.1 的教程

当我运行这些教程时,我得到 NullPointerExceptions,其中使用 java.net.URL 加载了新的 ImageIcon。

// generate a terrain texture with 3 textures
ProceduralTextureGenerator pt = new ProceduralTextureGenerator(heightMap);
pt.addTexture(new ImageIcon(Lesson3.class.getClassLoader().getResource("path/to/file")), -128, 0, 128); //line 199
pt.addTexture(new ImageIcon(Lesson3.class.getClassLoader().getResource("dirt.jpg")), 0, 128, 255);
pt.addTexture(new ImageIcon(Lesson3.class.getClassLoader().getResource("highest.jpg")), 128, 255, 384);
pt.createTexture(32);

但是,当我将文件路径解析为字符串而不是将它们读取为 java.net.URL 时,它们可以正常工作。

例如: new ImageIcon("path/to/file")

这是堆栈跟踪

Jun 4, 2011 4:18:22 PM class jme.test.Lesson3 start()
SEVERE: Exception in game loop
java.lang.NullPointerException
at javax.swing.ImageIcon.(ImageIcon.java:167)
at jme.test.Lesson3.buildTerrain(Lesson3.java:199)
at jme.test.Lesson3.initGame(Lesson3.java:151)
at com.jme.app.BaseGame.start(BaseGame.java:74)
at jme.test.Lesson3.main(Lesson3.java:62)
at jme.test.Main.main(Main.java:14)
Jun 4, 2011 4:18:22 PM com.jme.app.BaseGame start
INFO: Application ending.

这可能是什么原因? 谢谢..

为了使用ClassLoader#getResource() ,资源需要在类路径中。

当它位于与第 3 课 class相同Lesson3中时,请执行此操作

new ImageIcon(Lesson3.class.getResource("image.png"));

如果它位于不同的 package 中,则使用从类路径根开始的绝对路径,即以/开头。

new ImageIcon(Lesson3.class.getResource("/com/example/image.png"));

这期望文件image.png位于 package com.example

不建议将new File()用于相对路径,因为它取决于当前工作目录,而当前工作目录又取决于您启动应用程序的方式,而这在应用程序内部是无法控制的。

如果您尝试获取相对于您的 class 的路径文件并且 getclass().get 资源不起作用,请使用文件。 用图像的名称创建一个文件并使用 new imageIcon(file.getAbsoltuePath);

我真的不能给你看一个例子,因为我在我的 iPad 上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM