Search code examples
javapaintcomponent

How to have a for loop increment height and pos


I am trying to have it so that my drawRect is created 13 times on the panel. This works correctly but I would also like it to start from a height of say 100 and increment up to 550. I am not sure how I would add the incrementation of the height as I have the draw rect in a for loop already.

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.Random;

import javax.swing.JPanel;

public class Draw extends JPanel
{
    Color rand;

    private int randRed() {
        int red;
        Random randomNumber = new Random();
        red = randomNumber.nextInt(255);
        return red;
    }

    private int randGreen() {
        int green;
        Random randomNumber = new Random();
        green = randomNumber.nextInt(255);
        return green;
    }

    private int randBlue() {
        int blue;
        Random randomNumber = new Random();
        blue = randomNumber.nextInt(255);
        return blue;
    }

    int newRectPos = 0;
    public void paintComponent(java.awt.Graphics g)
    { 
        super.paintComponent(g);

        for (int i = 0; i < 550; i ++)
        {

        }

        for (int j = 0; j <= 800; j = j + 60; int i = 0; i <= 550; i ++)
        {
            g.setColor(new Color(randRed(), randGreen(), randBlue()));
            g.drawRect(j, 0, 60, 550);
            g.fillRect(j, 0, 60, 550);
            repaint();

        }
    }
}

Solution

  • Instead of

    for (int j = 0; j <= 800; j = j + 60; int i = 0; i <= 550; i ++)

    You can write

    for (int j = 0; j <= 800 && j <= 550; j += 60, i ++)
    

    or as a nested loop of

    for (int j = 0; j <= 800; j = j + 60) 
        for(int i = 0; i <= 550; i ++)