Tarc
Tarc

Reputation: 370

getSubimage throwing a NullPointerException for an unknown reason

Well, I'm trying to make a graphical game for the first time, but:

BufferedImage tileset = null;
try{
    tileset = ImageIO.read(new File("sets/tiles.png"));
}
catch(IOException e){
    System.out.println(e.toString());
}
MwatRoot.allTiles[0].tile = tileset.getSubimage(0, 0, 32, 32);
MwatRoot.allTiles[1].tile = tileset.getSubimage(0, 32, 32, 32);

this is throwing a NullPointerException:

MwatRoot.allTiles[0].tile = tileset.getSubimage(0, 0, 32, 32);
MwatRoot.allTiles[1].tile = tileset.getSubimage(0, 32, 32, 32);

this is allTiles:

public static TileClass[] allTiles = new TileClass[2];

and TileClass:

public class TileClass {
    public BufferedImage tile;
    public boolean BlocksMovement;
}

Can someone explain to me why that is happening? I already checked, tileset isn't null.

Upvotes: 0

Views: 299

Answers (1)

Adel Boutros
Adel Boutros

Reputation: 10285

public static TileClass[] allTiles = new TileClass[2];

this does not correctly initialise the array.

You have to add after it, the following:

allTiles[0] = new TileClass();
allTiles[1] = new TileClass();

Upvotes: 3

Related Questions