Search code examples
javaswingjava-2dpaintcomponent

While statement in paintComponent


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--;
        }
    }
}

Solution

  • Change

    while(numOfTiles > 0){ 
    

    to

    // or the more modern variant shown by Kumar
    for (int count=0; count<numOfTiles; count++) { 
    

    and remove:

        numOfTiles--;
    

    Explanation. I suspect numOfTiles is being reduced to 0 in the first paint and never gets reset. The for loop takes care of that by never changing the value.

    Also note Walter's tweak:

        g.drawImage (chosenTile, tileStartx + (count * 10), tileStarty, this); 
    

    instead of:

        g.drawImage (chosenTile, tileStartx, tileStarty, this);
        tileStartx += 10;