-1

Hey i am making a game in java and while loading the tilesheet I get a weird error and i cant fin out why.

public class TileSheetLoader {

BufferedImage tileSheet;

int width;
int height;
int rows;
int cols;
public BufferedImage[] tiles;

public void loader(int width, int height, int rows, int cols)
{
    try
    {
         ImageIO.read(new File("gfx/tileSheet.png"));
    }catch(Exception e){System.out.println("Couldent load tileSheet.png");}
    this.width = width;
    this.height = height;
    this.rows = rows;
    this.cols = cols;
    this.tiles = new BufferedImage[rows * cols];
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            tiles[(i * cols) + j] = tileSheet.getSubimage(i * width, j * height, width, height);
            System.out.println("loaded tile");
        }
    }
}

}

This is the code of the class. I get the NullPointException on this line

tiles[(i * cols) + j] = tileSheet.getSubimage(i * width, j * height, width, height);

this is where i call the methode.

tilesheetloader.loader(96, 32, 1, 3);

already a big thanks for the people who took the time to read.

  • 2
    Most importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). **You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully**, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. – Hovercraft Full Of Eels Jan 03 '15 at 21:29

2 Answers2

5

You didn't allocate memory for tileSheet.

Remember: complex data types must be allocated with new.

I think you wanted to do this, but forgot to capture the return of ImageIO.read():

tileSheet = ImageIO.read(new File("gfx/tileSheet.png"));
karlphillip
  • 92,053
  • 36
  • 243
  • 426
1

tileSheet is never instantiated with new keyword so it is null, and you are calling a method on a null value... thus NPE

probably what you wanted to do is stuff ImageIO.read() into tileSheet... once you put the return value of ImageIO.read() into tileSheet, it is not longer null, and you can call a method on the object

Josh Engelsma
  • 2,636
  • 14
  • 17