NullPointExceptionError help needed

Escape :

I would like to apply icons to my program, but it gives me an error. It looks all good, that is why I dont have a clue what is wrong with it.

public static ImageIcon createIcon (String path) {
    URL url = System.class.getResource(path);

    if(url == null) {
        System.err.println("Unable to load image: " + path);
    }

    ImageIcon icon = new ImageIcon(url); //here is line 30 in class Utils

    return icon;
}

And his is the error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    at gui.Utils.createIcon(Utils.java:30)
Arvind Kumar Avinash :

The problem is that url is null. Check how the constructor has been implemented:

public ImageIcon (URL location) {
    this(location, location.toExternalForm());
}

If location is null, location.toExternalForm() will throw NullPointerException.

In fact, if path is null, that too can cause NullPointerException. See how getResource has been implemented.

public URL getResource(String name) {
    name = resolveName(name);
    //...
}

private String resolveName(String name) {
    if (!name.startsWith("/")) {
        Class<?> c = this;
        while (c.isArray()) {
            c = c.getComponentType();
        }
        String baseName = c.getPackageName();
        if (baseName != null && !baseName.isEmpty()) {
            name = baseName.replace('.', '/') + "/" + name;
        }
    } else {
        name = name.substring(1);
    }
    return name;
}

As you can see, if name is null, name.startsWith("/") will throw NullPointerException.

Do it as follows:

public static ImageIcon createIcon (String path) {
    if(path == null) {
        System.err.println("Path is null");
        return null;
    }

    URL url = System.class.getResource(path);
    ImageIcon icon = null;

    if(url != null) {
        icon = new ImageIcon(url);
    } else {
        System.err.println("Unable to load image: " + path);
    }

    return icon;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=355912&siteId=1