-2

I'm making a game but when i tried to launch it it said: java.lang.NullPointerException.

Here is the code:

package com.shinxs.rain.graphics;

import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
import javax.swing.ImageIcon;

public class Screen {

    private int width, height;
    public int[] pixels;
    Graphics g;

    public int[] tiles = new int[64 * 64];

    private Random random = new Random();

    ImageIcon i = new ImageIcon("Resources/Inventory.png");
    Image image = i.getImage();

    public Screen(int width, int height) {
        this.width = width;
        this.height = height;
        pixels = new int[width * height];

        for (int i = 0; i < 64 * 64; i++) {
            tiles[i] = random.nextInt(0xFFFFFF);
        }
    }

    public void clear() {
        for (int i = 0; i < pixels.length; i++) {
            pixels[i] = 0;
        }       
    }

    public void render() {
        g.drawImage(image, 500, 200, 124, 280, null);
    }
}

Please tell me if you know how to fix it, I've been stuck with it for a long time.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Shinxs
  • 21
  • 7

3 Answers3

4
 Graphics g;

Your g is pointing to null-reference and you are calling drawImage on null which is resulting in NPE (NullPointerException).

g.drawImage(image, 500, 200, 124, 280, null);

See this tutorial on how to use Graphics in java

kosa
  • 65,990
  • 13
  • 130
  • 167
1

Your Graphics object is null because you never assign to any other value. Null means that an object is "empty" and contains no data, which is a logical value for objects to be initialized to. In order to use a Graphics object, you need to get access to a pre-made one, as the Graphics class has no public constructor (new Graphics() does not work). The only way I know of to do this is to extend javax.swing.JFrame and override the paint(Graphics g), in which a pre-instantiated Graphics object is passed as an argument. The Graphics object is created by the internal workings of the JFrame.

   class Screen extends javax.swing.JFrame{

         public void paint(Graphics g){
                super.paint(g); //correctly draws background

                //now call methods on g, the graphics object
         }
   }

I would highly recommend looking into the documentation on Swing, to find out more about how it works.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
0

you never initialiazed your Graphics g;object and calling methods on it, you have to initialize your Graphics object, otherwise it'd be null, as objects default value is null.

Graphics g= Griphics.create();

g.darwLine()
PermGenError
  • 45,977
  • 8
  • 87
  • 106