即使图像位于我指定的路径中,图像图标仍返回空指针异常

时间:2019-05-03 16:51:15

标签: java swing netbeans embedded-resource imageicon

我正在尝试在应用程序中放置图像,但总是出现nullpointerexception错误。我将图像放在名为“ res”的程序包中,并将路径指定为(getClass()。getResource(“ / res / BargainG.png”)),但它似乎对我不起作用。有人可以告诉我我在做什么错吗?

image place

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/BargainG.png")));

这是我得到的错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at com.BargainG.BargainG.initComponents(BargainG.java:227)
at com.BargainG.BargainG.<init>(BargainG.java:20)
at com.BargainG.BargainG$8.run(BargainG.java:357)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

2 个答案:

答案 0 :(得分:0)

尝试

ClassLoader.getSystemResource("/res/BargainG.png")

或带有

getClass().getClassLoader().getResource("/res/BargainG.png")

答案 1 :(得分:-1)

您可以尝试使用以下代码获取图像:

ImageIO.read(getClass().getResourceAsStream("/BargainG.png"));

确保“ res”文件夹位于构建路径内。