首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中添加ImageIcon?此代码不起作用。

如何在java中添加ImageIcon?此代码不起作用。
EN

Stack Overflow用户
提问于 2020-11-30 11:56:49
回答 2查看 10.4K关注 0票数 3

我想在面板中添加一个ImageIcon,但是我得到了这个异常(

代码语言:javascript
复制
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“是空,而我不知道如何解决它,请帮帮我。

代码语言:javascript
复制
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);
    }
}
EN

回答 2

Stack Overflow用户

发布于 2021-11-26 23:56:55

代码语言:javascript
复制
public ImageIcon image = new ImageIcon(Test.class.getResource("give image path"));

请这边试试。在文件结构中给出图像路径。

票数 -1
EN

Stack Overflow用户

发布于 2022-04-10 12:53:42

这可能会有帮助

代码语言:javascript
复制
ICON = new ImageIcon("specify icon path here "); 

//you might need to scale the icons size 
Image image = image.getImage().getScaledInstance(width, height,Image.SCALE_DEFAULT);

ImageIcon ICON2 = new ImageIcon(image);

LABEL2 = new JLabel(ICON2);

LABEL2.setBounds(x,y,width,height);
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65073109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档