I am trying to make a simple tile system for my game. I made a test tile and I am trying to paint 5 tiles next to each other. I made a while statement in my paintComponent where it counts down from 5 and each time it draws one tile and adds 10 (size of the tile) to the current x value. But for some reason none of the tiles shows up. If I comment out the while statement one tile shows up. So the image is being loaded. For some reason the while statement messes the painting up. Would really appreciate some help.
Here is my code from my paintComponents
- the variable numOfTiles = 5
- the variable tileStartx = 100;
- the variable chosenTile is my image.
public void paintComponent(Graphics g){
super.paintComponent(g);
if(tileToDraw != null){
while(numOfTiles > 0){
System.out.println(tileStartx);
g.drawImage (chosenTile, tileStartx, tileStarty, this);
tileStartx += 10;
numOfTiles--;
}
}
}
Change
to
and remove:
Explanation. I suspect
numOfTilesis being reduced to 0 in the first paint and never gets reset. Theforloop takes care of that by never changing the value.Also note Walter’s tweak:
instead of: