Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

classpath - Java: NullPointerException from class.getResource( ... )

I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:

prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));

Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).

I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?

Edit: someone asked for my folder hierarchy:

Folder Hierarchy

I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.

Edit 2:

System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);

Prints true.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.

Try the following:

getClass().getClassLoader().getResource("/icons/icon_prayer.png")

Or:

ClassLoader.getSystemResource("/icons/icon_prayer.png")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...