使用路径名加载图像文件时出现NullPointerException [英] NullPointerException when using path name to load image file
问题描述
在使用NetBeans时,无处不在,仍无法找到解决此问题的方法。
Looked everywhere and still can't find a solution to this problem while using NetBeans.
当我使用以下代码按路径加载文件时:
When I use the following code to load a file by path:
Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage();
我得到一个NullPointerException。我在某处建议创建一个新文件夹并将其作为项目的源文件,但这没有用。我尝试过在本网站和其他网站上发现的多项建议,但我没有得到任何结果。
I get a NullPointerException. I read somewhere where it suggested creating a new folder and making it a source file for the project, but that didn't help. I've tried multiple suggestions that I found on this site and others, but I'm not getting any results.
我开始怀疑是否有什么问题我正在把路径放进去的方式,但我完全按照它在其他地方显示的方式来做。我已经尝试了过去几天我能找到解决这个问题的每个例子的每个组合,但没有任何工作。
I'm starting to wonder if there is something wrong with the way that I am putting the path in, but I'm doing it exactly the way that it shows everywhere else. I've tried every combination of every example that I could find to solve this problem for the last couple of days, but nothing is working.
推荐答案
似乎 images
文件夹不属于您的类路径。在Eclipse中,它不在他们所谓的构建路径中。
It seems like the images
folder wasn't part of your classpath. In Eclipse, it's not in what they call the Build Path.
右键单击 images
文件夹,选择构建路径并用作源文件夹。现在,只要您通过Eclipse运行应用程序,该文件夹就会添加到类路径中。如果你这样做,你需要改变你的路径
Right-click on the images
folder, select Build Path and Use as Source Folder. The folder will now be added to the classpath whenever you run your application through Eclipse. If you do this, you need to change your path to
Image owl = new ImageIcon(this.getClass().getResource("/owl.gif")).getImage();
因为现在 images
中的所有内容都会被放入直接在类路径上。
because now everything in images
will be put directly on the classpath.
您可以在正常 images
的包> src 文件夹并将其称为
You could instead, make a package called images
under your normal src
folder and call it as
Image owl = new ImageIcon(this.getClass().getResource("/images/owl.gif")).getImage();
这篇关于使用路径名加载图像文件时出现NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!