Sign in to follow this  
PsionicTransvection

Problem with JAVA ImageIcon

Recommended Posts

[CODE]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();
}
}[/CODE]

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
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 [url="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)"]http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)[/url].

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this