Skip to main content
gamedev.net
🔒 Locked

Problem with JAVA ImageIcon

Started by PsionicTransvection Jun 8, 2012 at 8:34 AM 6 replies 2.3k views
Original Post
PsionicTransvection
PsionicTransvection
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 cant 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.(ImageIcon.java:167)
at View.(View.java:14)
at View.main(View.java:30)
RulerOfNothing
RulerOfNothing
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?
PsionicTransvection
PsionicTransvection
same exception different line in another program I have done the assignment the same way outside the constructor checked path everything still getting the NullPointerException
RulerOfNothing
RulerOfNothing
Alright, what happens if you remove the slash in the filename?
fae
fae
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).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.