Search code examples
javanullpointerexceptionjava-3d

Null Pointer Exception at Graphics.drawImage()


This is the code I am using to draw an image on a J3D Canvas3D:

    Graphics g = Canvas.getGraphics(); //Canvas is the Canvas3D
    g.drawImage(new ImageIcon("back/loadingscreen.png").getImage(),
            0, 0, Canvas);

however whenever I run the code I get a NullPointerException at the line of g.drawImage(). I have no idea what is causing the exception, help would be appreciated.


Solution

  • Your ImageIcon is null please use this to load your ImageIcon properly

     InputStream stream = this.getClass().getClassLoader().getResourceAsStream("back/loadingscreen.png");
         BufferedImage bufferedImage=ImageIO.read(stream);
         ImageIcon icon= new ImageIcon(bufferedImage);
    
         Graphics g = Canvas.getGraphics(); 
            g.drawImage(icon.getImage(), 0, 0, Canvas);