如何在java中添加imageicon?此代码无效

jc3wubiy  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(518)

我想在面板上添加一个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);
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题