Reputation: 103
public class Intro extends JFrame implements ActionListener {
ImageIcon pic = new ImageIcon(this.getClass().getResource("cars-games.jpg"));
JLabel l1 = new JLabel();
Image car = pic.getImage();
public static void main (String[]args){
Intro i = new Intro();
i.show();
}
}
Its giving me this error:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Intro.<init>(Intro.java:15)
at Intro.main(Intro.java:58)
Can anyone help plz.
Upvotes: 0
Views: 109
Reputation:
I was getting this issue a lot at the beginning of development for my java game project for this semester. This generally means that the resource that you are trying to access is not able to be found (i.e. Nullpointerexception). What I did to make everything much easier was to just make a separate folder in your java project called images (especially if you are using multiple images in this project). Then you can just call new ImageIcon with your directory. Makes things a lot easier in the end.
As stated earlier, getClassLoader() works as well!
Upvotes: 0
Reputation: 34397
I think it's not able to read your image file and hence the issue.
Try using classLoader
as :
ImageIcon pic = new ImageIcon(getClass().getClassLoader()
.getResource("cars-games.jpg"));
If still you get the same issue then make sure that cars-games.jpg
is available in root of your class loader location.
Upvotes: 1
Reputation: 28707
Your resource is null, and ImageIcons cannot be constructed with null parameters.
Make sure you've entered the correct path to "cars-games.jpg".
Upvotes: 4