gpt4 book ai didi

java - 如何在java中添加一个ImageIcon?此代码无效

转载 作者:行者123 更新时间:2023-12-05 08:11:03 25 4
gpt4 key购买 nike

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

最佳答案

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

请试试这个方法。在你的文件结构中给出图像路径。

关于java - 如何在java中添加一个ImageIcon?此代码无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65073109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com