我正在运行此代码,并且它返回了以下堆栈跟踪:
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:115)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:125)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:263)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)
我不知道我输错Null Pointer异常的地方。关于如何解决这个问题的提示?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class MyFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel() {
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(
MyFrame.class.getResource("/images/Ella and Louis_front.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane); }
}
答案 0 :(得分:1)
获取资源时:MyFrame.class.getResource("/images/Ella and Louis_front.jpg")
它返回一个null
,我建议做一个检查:
我建议做一个检查:
URL url = MyFrame.class.getResource("/images/Ella and Louis_front.jpg")
if (url != null) {
Image img = Toolkit.getDefaultToolkit().getImage(url);
}