Reputation: 5355
I want to display another icon instead of the usual java load icon. I have put that into this folder:
I want to load it over the getResource()
method.
setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("house.png")));
However, I am getting:
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
Why does getResource()
not load my picture from my folder? I appreciate your answer!
Upvotes: 1
Views: 1958
Reputation: 121
Для того чтобы и сборка была корректная, можно использовать вот это:
ImageIcon icon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(this.getClass().getResource("logo.png")));
Upvotes: 0
Reputation: 208994
Just for an explanation of why @MadProgrammer's comment ("/house.png"
) worked:
You are using maven. Files in src/main/resources
become resources on the class path. Ultimately placed at the root of the classpath, with no main/resources
. So you're intuition was correct, initially just using "house.png"
as the path, as the image is at the root.
What you failed to consider though is where the call is coming from. When you use Class.getResource
, the call will begin the search from the location of the class, i.e the package where the calling class is located. So for instance if you have something like
src
main
resources
house.png
main
java
com
mypackage
CallingClass.class
The search will being in com/mypackage
. So for this path ("house.png"
) to work, the image would have to be in the com/mypackage
package, but it's not. It's in the root.
That brings us to the forward slash /
. That that forward slash ultimately does, is make the search start from the root of the class path. So with the forward slash ("/house.png"
), the search will find the image in src/main/resources
, which ultimately in the root of the classpath.
Upvotes: 3
Reputation: 540
Use the following:
setIconImage( Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("house.png")));
or
setIconImage( Toolkit.getDefaultToolkit().getImage(MainWindow.class.getClassLoader().getResource("house.png")));
Upvotes: 0