问题
I am studying Java Swing library and I have a problem.
In an example program it create an ImageIcon object by this line:
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
Whe I execute my program I obtain the following error caused by the fact that in the project the exit.png is missing:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at com.andrea.second.SimpleMenu.initUI(SimpleMenu.java:23)
at com.andrea.second.SimpleMenu.<init>(SimpleMenu.java:17)
at com.andrea.second.SimpleMenu$2.run(SimpleMenu.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)
The problem is, using Eclipse, where I have to put this immage?
I tryed to copy and paste it (in my file system, not in Eclipse) an "exit.png" file into the same package folder that contains the class that create it...but it don't work
What have I to do to solve this problem in Eclipse?
回答1:
With
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
You need to put the exit.png
in the same package as the Class represented by getClass()
.
With
ImageIcon icon = new ImageIcon(getClass().getResource("/exit.png")); // note leading /
You need to put it at the root of your classpath. In Eclipse, that would happen by putting it directly in src
.
The Class#getResource(String) javadoc states
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), 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 Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
来源:https://stackoverflow.com/questions/19007945/where-have-i-to-put-an-image-to-use-it-to-create-a-new-swing-imageicon-object