Question

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.

Was it helpful?

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);

OTHER TIPS

Try something like this:

Graphics g = Canvas.getGraphics();

if(g==null){

System.out.println("Did not receive any Graphics object from the getGraphics method.");

}

ImageIcon icon = new ImageIcon("back/loadingscreen.png");

if(icon==null){

System.out.println("The icon is not received meaning the URL path (back/laodingscreen.png) is probably wrong.");

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top