Johanna Johanna - 2 years ago 122
Java Question

Why does my icon handling code throw a NullPointerException?

I have added an image for my button,but when I run that frame this exception will be thrown .why?please help me.


Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(
at ClientGUI.IdAndPasswordFrame.initComponents(
at ClientGUI.IdAndPasswordFrame.<init>(
at ClientGUI.IdAndPasswordFrame$
at java.awt.event.InvocationEvent.dispatch(
at java.awt.EventQueue.dispatchEvent(
at java.awt.EventDispatchThread.pumpOneEventForFilters(
at java.awt.EventDispatchThread.pumpEventsForFilter(
at java.awt.EventDispatchThread.pumpEventsForHierarchy(
at java.awt.EventDispatchThread.pumpEvents(
at java.awt.EventDispatchThread.pumpEvents(
BUILD SUCCESSFUL (total time: 1 second)

line 138:

public ImageIcon (URL location) {
this(location, location.toExternalForm());


jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/yahoo_1.gif"))); // NOI18N

I use this poor checking (Peter Lang recommended)which is:System.out.println(getClass().getResource("/Images/yahoo_1.gif")); and it returns null,why? please help me.

Answer Source

This means, that getClass().getResource("/Images/yahoo_1.gif") returns null.

JavaDoc states that this happens if

the resource could not be found or the invoker doesn't have adequate privileges to get the resource.

  1. Check if getResource really returns null:

  2. Make sure that your path is correct and that it is in your classpath.


I just tried it with NetBeans. I created the following structure

Source Packages

and your code worked fine. Is this your structure?

Try to right-click on your application and select Clean and Build.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download