简体   繁体   中英

NPE when getting resource

I am trying to get an image from the resource folder of my java application. However, no matter in which way I try to get the resource, it gives me a NPE.

This is my code:

JLabel lbl_pic;
ImageIcon i = new ImageIcon(getClass().getClassLoader().getResource("res/img/user.png")); //NPE occurres here
lbl_pic = new JLabel(i);

My NetBeans project folder looks like this:

ProjectName
    >Source Packages
        >com.scfa.projectName
            >main.java
        >com.scfa.projectName.res.img
            >user.png

Can somebody please tell me, what I have done wrong?

I already looked at the following topics, but couldn't get it working:

Thanks a lot for your help i advance :)

You seem to be saying that the user.png is in the package com.scfa.projectName.res.img

In that case, you can get its URL using:

URL url = getClass().getClassLoader().getResource(
    "/com/scfa/projectName/res/img/u‌​ser.png");  // absolute path

or

URL url = getClass().getResource("res/img/user.png"); // relative path

In general, if you want to resolve a resource path relative to a class, you must call getResource on the Class object ... not on its classloader. The getResource method for a ClassLoader object will treat a relative resource path as if it was an absolute resource path. The same applies to the getResourceAsStream methods on Class and ClassLoader .

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