SpriteSheet loading class returns error when there seems to be none

Class Here

Hi again,

This is a spritesheet loading class that gets a buffered image, the amount of tiles in the x and y directions and then splits the image into it’s subimages and puts it into an appropriately sized array. Problem is, I start getting a rasterformatexception halfway through the first row, saying that (x + width) is outside the raster. Thing is, when I print the amount of space left on the x-axis for the picture, I’m only halfway through loading it. I’ve only tested it with a single spritesheet that is sized at 192x128. Every time I’ve looked at the class, everything seems in order. It runs fine for the first four, I’m even able to display the images it successfully loads (Albeit anything after the first image contains all the previous images).

I figure I must be leaving something out, since I’m new to using a BufferedImage, having used only ImageIcons before. So anyone with some more experience have a modification to the code that could help me out? Appreciate any help.

Edit: Ooops this version is the wrong one. Going to put the right one up in a sec.

Edit 2: Updated.

I’m going to try not to be mean here, but this is not well written code. At least, the for loop you have is very bad. It’s difficult to read and understand which means that it’s probably not doing what you think it is.

I think what’s going on here, is that you never reset the i variable. So, after the first time i == tilesX, it will never trigger that if again and spill off the edge of the sheet.

A better way to do this would be as a nested set of for loops…


for(int i = 0, index = 0; i < tilesX; i++) {
for(int j = 0; j < tilesY; j++, index++) {
tiles[index] = sprites.getSubImag(i * sizeX, j * sizeY, (i + 1) * sizeX, (j+1) * sizeY);
}
}

Edit: Added a bit to my description of why it’s bad. ^^;

Thanks for the honesty. You were right. It wasn’t tripping my crappy fail safe.

Thanks UprightPath you helped me get it working.

I also agree the code is very badly written, this shows you’re not really ready for graphics yet. Learn more Java and OO then when you feel you’re comfortable enough with Java, jump into graphics.