【发布时间】:2021-03-12 08:21:04
【问题描述】:
我想在面板中添加一个 ImageIcon,但我得到了这个异常 (
java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "javax.swing.JLabel.setBounds(int, int, int, int)"
因为“this.LABEL2”为空,我不知道如何解决,请帮帮我。
import javax.swing.*;
import java.awt.*;
public class ShowQR extends JFrame{
private JPanel PANEL;
private JLabel LABEL2;
private ImageIcon ICON;
public ShowQR(){
super("Choose background color");
ICON = new ImageIcon(getClass().getResource("qr-code2.png"));
LABEL2= new JLabel(ICON);
PANEL.setLayout(null);
LABEL2.setBounds(50, 50, 50, 50);
PANEL.add(LABEL2);
add(PANEL);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,400);
}
}
【问题讨论】:
-
这里的根本原因可能是,在此路径中找不到您指定的图像。您是否确保指定了正确的图像路径? How to use Icons 上的 java 教程有一些关于如何正确加载图像的好例子。
-
ICON = new ImageIcon(getClass().getResource("qr-code2.png"));你确定icon不为空并且qr-code2.png位于预期的位置。 -
变量名不应大写。学习并遵循 Java 命名约定。您可以在教科书或在线教程中找到的任何代码示例中找到适当的约定。
标签: java swing nullpointerexception embedded-resource imageicon