Jump to content
  • Advertisement
Sign in to follow this  
PsionicTransvection

Problem with JAVA ImageIcon

This topic is 2227 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class View extends JFrame
{

JPanel jp = new JPanel();
JLabel jl1 = new JLabel();
ImageIcon figure = new ImageIcon(getClass().getResource("/blank.png")); // I get the exception here

public View(){
setTitle("test");
setSize(800, 600);
setResizable(false);
setVisible(true);
setLocationRelativeTo(null);
jl1.setIcon(figure);
jp.add(jl1);
add(jp);
jl1.setBounds(0, 0, jl1.getIcon().getIconWidth(), jl1.getIcon()
.getIconHeight());
validate();
}
public static void main(String[] args){
new View();
}
}


for some reason I can`t fetch the image and the path and name is correct checked it several times
and the funny thing is I`m doing it by checking some old code of mine and there is working perfectly ...
This is the exception I get any Ideas ?

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
at View.<init>(View.java:14)
at View.main(View.java:30)

Share this post


Link to post
Share on other sites
Advertisement
I think the problem is that you are trying to access member functions of the View class before it is constructed. What happens if you move the assignment of figure to the constructor?

Share this post


Link to post
Share on other sites
This is normal behavior. The getResource method of the Class delegates the call to the ClassLoader, which looks for the resource in class path. Your call basically asked for a resource called "blank.jpg" at the root of the class path (not the file system root). If you want to load resources outside class path you can use e.g. java.io.File class.

The NullPointerException you got was from the ImageIcon constructor. This happened because the getResource method returned null for a resource that it couldn't find. For more info see http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!