Reputation: 13
I'm getting weird path problems even after I've checked them, any clue whats up with this? I checked my error online and apparently its path problem, even though I check the path just before...
java.net.URL imgURL = getClass().getResource("/resources/image.gif");
if (imgURL != null) {
System.out.println("Working!!");
} else {
System.out.println("Couldn't find file: " + "/resources/image.gif");
}
JButton submitButton = new JButton(new ImageIcon(getClass().getClassLoader().getResource("/resources/image.gif")));
Output is:
Working!!
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at javaapplication17.JavaApplication17.initUI(JavaApplication17.java:38)
at javaapplication17.JavaApplication17.<init>(JavaApplication17.java:22)
at javaapplication17.JavaApplication17$1.run(JavaApplication17.java:53)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Upvotes: 0
Views: 63
Reputation: 51030
Don't add the leading /
, in the path, while using the ClassLoader
instance. It is required only when you do getResource()
on Class
instance to tell that the path starts at the root of the classpath. In case of classloader the path is assumed to be starting at the root of the classpath.
So the actual difference is the usage of Class#getResource()
in one case and the ClassLoader#getResource()
in the other.
In both cases, either do
//using classloader, path does not start with /
getClass().getClassLoader().getResource("resources/image.gif")
or do
//using class, path starts with /
getClass().getResource("/resources/image.gif")
Upvotes: 2
Reputation: 5598
in the first case you have
getClass().getResource("/resources/image.gif");
and in the second
getClass().getClassLoader().getResource("/resources/image.gif")
is this difference causing the problem?
Upvotes: 0
Reputation: 16060
You check the resource to be not null in one ClassLoader and try to load from another ClassLoader (The may be different).
Upvotes: 0