java - 如何在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);
}
}
解决方案
public ImageIcon image = new ImageIcon(Test.class.getResource("give image path"));
请尝试这种方式。给出文件结构中的图像路径。
推荐阅读
- .net - Acumatica - 具有计算功能的 PXDBScalar
- reactjs - React Material UI:使文本字段保持在一行
- spring-boot - Apache Camel JMS/AMQP 组件仅在需要时创建目标队列
- if-statement - 如何修复:在关联列表中移动列时键入错误
- spring-data-jpa - NativeSql 查询到 JPQL 查询转换
- swift - 如何快速沿折线移动标记
- angular - 无法在 Angular7 中向我的请求 API 添加标头
- python - 如何在python flask form post api中加载和读取excel文件
- python - 用 Matplotlib 和 Pandas 绘制日期
- thingsboard - 如何从 Thingsboard 中删除旧事件?