如何使用getClass()。getResource()方法 [英] How to use getClass().getResource() method
问题描述
当我创建ImageIcon类对象时,我使用以下代码:
iconX = new ImageIcon (getClass().getResource("imageX.png"))
当.png位于同一个文件夹中时,上述代码可以在applet或桌面应用程序中正常工作。
The above code works correctly either in an applet or a desktop app when the .png is in the same folder of the class.
问题是:如何当.Png在另一个文件夹中时,避免 NullPointerException
?或者当对象位于该类的不同位置时,如何在对象 ImageIcon
中加载图像?
The question is: how to avoid a NullPointerException
when the .Png is in another folder? Or how load the image in the object ImageIcon
when it is in a different location to the class?
我不喜欢我不明白这种方法是如何运作的,如果有人能帮助我,我会很感激。谢谢!!
I don't understand how this method works, if anyone can help me I appreciate it. Thanks!!
推荐答案
看看这个 - Class#getResource(java.lang.String)
Take a look at this - Class#getResource(java.lang.String)
请点击上面的链接阅读文档,然后按照了解发生了什么。
Please click the link above and read the docs and follow to understand what's going on.
它说 -
如果名称以'/'开头,那么资源的绝对名称就是部分'/'之后的名称。
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
和
否则,绝对名称的格式如下:
Otherwise, the absolute name is of the following form:
modified_package_name/name
其中modified_package_name是此对象的包名称,其中'/'替换为'。'。
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
所以,如果这个对象(你调用 getResource $ c) $ c>)包在
/ pkg1
( /
意味着pkg1正好位于类路径的根目录下)并且你使用imageX.png然后结果将是 pkg1 / imageX.png
这是正确的,因为这是图像所在的位置。
So, if this object (where you call getResource
) is in package /pkg1
(/
meaning pkg1 is right under the root of the classpath) and you used "imageX.png" then the result would be pkg1/imageX.png
which is correct because that's where the image is located at.
但是,如果我们将资源(imageX.png)移动到其他包 / pkg2
并且您以同样的方式调用该方法,那么结果仍然是 pkg1 / imageX.png
但这次不正确,因为该资源实际位于 / pkg2
。那是你最终得到NPE的时候。
But, if we moved the resource (imageX.png) to some other package /pkg2
and you called the method same way then the result would still be pkg1/imageX.png
but this time it would be incorrect because the resource is actually located in /pkg2
. That's when you end up with NPE.
从类路径的根开始明确指定资源的完整路径是件好事。 (例如/pkg/imageX.png)。
It's good to explicitly specify the full path of the resource starting from the root of the classpath. (e.g. "/pkg/imageX.png").
希望这有帮助。
这篇关于如何使用getClass()。getResource()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!