When I Run My Code, I Get this Error:
Exception in thread "main" java.lang.NullPointerException
at Main.drawBlock(Main.java:48)
at Main.<init>(Main.java:43)
at Main.main(Main.java:58)
I Think this is Because of The Graphics that I Drew, But That Never Happened Before. I Have No Idea WHY. Here is My Code:
Graphics2D g;
static JFrame jf = new JFrame();
Image Air;
Image Grass;
Image icon;
public Main() {
icon = new ImageIcon(this.getClass().getResource("Icon.png")).getImage();
Grass = new ImageIcon(this.getClass().getResource("Grass.png")).getImage();
Air = new ImageIcon(this.getClass().getResource("Air.png")).getImage();
jf.setIconImage(icon);
drawBlock(Air,0,0);
}
private void drawBlock(Image img, int x, int y) {
g.drawImage(img,x,y,null);
}
public static void main(String[] args) {
jf.setSize(792,528);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.setTitle("Minecraft 2D Adventure");
new Main();
}}
Because you have not initialized Graphics2D g
so g is null
The real Reason of NPE
is Graphics2D
is a AbstractClass
and you can not instantiate it.
You can create instance of Graphics2D
instance like below
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
env.createGraphics(BufferedImage);
or you can use createGraphics()
From BufferedImage
public Graphics2D createGraphics()