这是我得到的错误:
Using directory file:/D:/CCSF%20Docs/CS111B/Java%20Projects/LabelDemo2.java/bin/
Image url is null
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at LabelDemo2.<init>(LabelDemo2.java:23)
at LabelDemo2.main(LabelDemo2.java:46)
有谁可以告诉我为什么我无法加载图片? java.jpg图像位于D:/CCSF%20Docs/CS111B/Java%20Projects/LabelDemo2.java/bin/
我不知道为什么我会收到空的异常/错误。
import java.awt.*;
import javax.swing.*;
public class LabelDemo2 extends JFrame {
private ImageIcon image1;
private JLabel label1;
private ImageIcon image2;
private JLabel label2;
private ImageIcon image3;
private JLabel label3;
private static final long serialVersionUID = 1L;
LabelDemo2() {
setLayout(new FlowLayout());
System.out.println("Using directory " + getClass().getResource(""));
System.out.println("Image url is " + getClass().getResource("java.jpg"));
image1 = new ImageIcon(getClass().getResource("java.jpg"));
label1 = new JLabel(image1);
add(label1);
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("java.jpg"));
label2 = new JLabel(image2);
add(label2);
image3 = new ImageIcon(getClass().getResource("java.jpg"));
label3 = new JLabel(image3);
add(label3);
}
public static void main (String args[]) {
LabelDemo2 gui = new LabelDemo2();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("Label Demo");
}
}
答案 0 :(得分:0)
如果image
位于您的源文件夹中,那么您确实如下所示阅读Image
getClass().getResource("/java.jpg")
只需添加/
或\\
如果它在您的源文件夹之外,那么您可以通过InputStream
以绝对路径
答案 1 :(得分:0)
你可以尝试
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream in = classLoader.getResourceAsStream(path);
OR
ClassPathResource fileReference = new ClassPathResource(filename);
InputStream in = fileReference.getInputStream();
OR
this.getClass().getResourceAsStream(filename);