Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

java - How to use getClass().getResource() method

When I create ImageIcon class objects I use the following code:

iconX = new ImageIcon (getClass().getResource("imageX.png"))

The above code works correctly either in an applet or a desktop app when the .png is in the same folder of the class.

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!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

It says -

If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.

and

Otherwise, the absolute name is of the following form:

     modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.'.

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.

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.

It's good to explicitly specify the full path of the resource starting from the root of the classpath. (e.g. "/pkg/imageX.png").

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...