我一直在互联网上搜索,试图找出如何将图标图像添加到我的 JFrame,但我不断收到错误消息。我知道堆栈溢出时有人问过这个问题,但解决方案对我不起作用。这是我的代码:
ImageIcon imageIcon = new ImageIcon("src/slime.png");
ImageIcon image = new ImageIcon("src/slime.gif");
JLabel label = new JLabel(image, JLabel.CENTER);
label.setAlignmentX(0);
label.setAlignmentY(0);
label.setIcon(image);
JFrame window = new JFrame("Slime");
window.setVisible(true);
window.setSize(250, 200);
window.setResizable(false);
window.setIconImage(newImageIcon(getClass().getResource("src/slime.png")).getImage());
window.add(label);
这是我得到的错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
at MainJFrame.<init>(MainJFrame.java:39)
at MainJFrame$1.run(MainJFrame.java:18)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
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)
帮助将不胜感激。注意:我试过 window.setIconImage(imageIcon.getImage()); 但这不起作用,并且使我在屏幕上打印的其他图像消失了。