Java – Exception in thread “main” java.lang.NullPointerException at javax.swing.ImageIcon.(Unknown Source)

exceptionjavanullpointerexception

I am working on a little program for school however I am getting this error whenever I run it:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Creatieve.Opracht.Main.main(Main.java:14)

The langugae I am coding in is Java, and before someone comments on it, no this is not a computer sience project so I can't ask a teacher.

This is de code I have written:

package Creatieve.Opracht;

import java.awt.*;
import javax.swing.*;

public class Main {
static JFrame frame;
static Puzzel puzzel;

public static void main(String[] args){
    frame = new JFrame("CKV Creatieve Oprdacht 2.0");
    frame.setSize(900, 900); //Lengte en breedte van de foto

    puzzel = new Puzzel(new ImageIcon(Main.class.getResource("/image.png")).getImage());
    frame.add(puzzel);

    frame.setVisible(true);


 }
}

And also this:

package Creatieve.Opracht;

import java.awt.*;
import javax.swing.*;

public class Puzzel extends JPanel{
Onderdeel[] onderdelen;
Image img;

public Puzzel(Image img){
    this.img = img;
    onderdelen = new Onderdeel[9];
    int onderdeelGrootte = img.getWidth(null)/3;
    for(int i = 0; i != onderdelen.length; i++){
        onderdelen[i] = new Onderdeel(this, i, onderdeelGrootte);
    }
}

public void paint(Graphics g){
    super.paint(g);
    for (int i = 0; i != onderdelen.length; i++){
        onderdelen[i].paint(g);
    }
 }
}

It would be awesome if one of you could tell me how I can fix the problem.

Thank you in advance!

Best Solution

Exception came on this line in your code when you are accessing image,
new ImageIcon(Main.class.getResource("/image.png")).getImage().

you have to check that /image.png image available at this location or not, if possible use qualified path name of your folder to resolve issue.

Related Question