0

I am trying to draw an image in my frame but I keep getting a NullPointerException. Here is what I have so far

package windows;
import BreezyGUI.*;

import java.awt.Graphics;
import java.awt.Label;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Title extends GBFrame{
    static Graphics g ;
    private BufferedImage bg;
    public Title(){
        bg = null;
        try {
            bg = ImageIO.read(new File("resources/images/TitleImage.png").toURI().toURL());
        } catch (IOException e) {
            e.printStackTrace();
        }
        g.drawImage(bg, 0, 0, null);
    }
}

but it always ends up printing:

Exception in thread "main" java.lang.NullPointerException
at windows.Title.<init>(Title.java:22)

The image i need, TitleImage.png, is inside the folder "images" in the source folder "resources".

Any help for a beginner is appreciated.

  • "what is a null pointer" dupe inc I can bet :p – Turtle Jan 25 '18 at 16:29
  • 4
    g isn't assigned. It is null – older coder Jan 25 '18 at 16:29
  • g is null and then you attempt to call drawImage, but g is null and therefore you get your null pointer exception – RAZ_Muh_Taz Jan 25 '18 at 16:31
  • 1
    g isn't assigned at all, let alone null - there's other code in the superclass GBFrame or else this doesn't compile. Which line is line 22? If I copy the text verbatim, I get a lone } as line 22 – antonyh Jan 25 '18 at 16:39
  • @antonyh a variable is null when it is not assigned a value or assigned a null value - they are one and the same. – Kleo G Jan 25 '18 at 16:42
  • Heh. I wonder which language I'm thinking of... thanks for educating me :-) – antonyh Jan 25 '18 at 16:52
  • Actually, I'm half right - if it's a declaration in a method, it does throw a compilation error like `Error:(7, 26) java: variable xyz might not have been initialized` - but if it's a static like in this question it assigns it to null. – antonyh Jan 25 '18 at 16:55

1 Answers1

0

your "g" isn't assigned. So when you try to call a method on it, it shows a NullPointerException. Hope it solves your problem ;) (another beginner)

Neamesis
  • 704
  • 1
  • 13
  • 28