Als
Als

Reputation: 43

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:

enter image description here

Upvotes: 0

Views: 2069

Answers (1)

Babak Behzadi
Babak Behzadi

Reputation: 1256

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'.

enter image description here

enter image description here

Upvotes: 2

Related Questions