首页 > 解决方案 > 如何在java中添加一个ImageIcon?此代码不起作用

问题描述

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

标签: javaswingnullpointerexceptionembedded-resourceimageicon

解决方案


public ImageIcon image = new ImageIcon(Test.class.getResource("give image path"));

请尝试这种方式。给出文件结构中的图像路径。


推荐阅读