简体   繁体   中英

Trying to set image icon for JLabel but URL returns null

Trying to set image icon for JLabel but returns a null URL?

I am using Netbeans and have included background.png in my project but it still returns null ?

import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class NewClass extends JFrame {

    JLabel o = new JLabel();

    public NewClass() {
        createImage("background.png");
        add(o);
        setVisible(true);
        setSize(100, 100);
        setResizable(false);
    }

    public static void main(String[] args) {
        new NewClass();
    }

    public void createImage(String str) {
        URL url = getClass().getResource(str);
        try {
            BufferedImage image = ImageIO.read(url);
            o.setIcon(new ImageIcon(image));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Error details in stack trace:

java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(ImageIO.java:1388)
    at Test.NewClass.createImage(NewClass.java:32)
    at Test.NewClass.<init>(NewClass.java:18)
    at Test.NewClass.main(NewClass.java:26)

Please could you help unsure why it doesn't work, when i try

JLabel o = new JLabel(new ImageIcon("background.png"); 

It works but this is error prone incase background.png doesn't exist? Thankyou

EDIT: components-SplitPaneDemo2Project - where this is name of netbeans project & background png is directly inside this folder

Located in here: C:\\Users\\John\\Documents\\NetBeansProjects\\components-SplitPaneDemo2Project

Screenshot:

在此处输入图片说明

I've tested your code with some changes and it works fine:

public class NewClass extends javax.swing.JFrame {

    JLabel o = new JLabel();

    public NewClass() {
        initComponents();

        createImage("background.png");
        add(o);
        setVisible(true);
        setSize(100, 100);
        setResizable(false);

        o.setLocation(20, 20);
        o.setSize(100, 25);
    }

    public void createImage(String str) {
        URL url = getClass().getResource(str);
        try {
            BufferedImage image = ImageIO.read(url);
            o.setIcon(new ImageIcon(image));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
....
}

in the constructor I've set location and size for 'o'.

'background.png' must be in the parent package of 'NewClass'.

在此处输入图片说明

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM