Click to See Complete Forum and Search --> : Grid of circles
yzobel
March 4th, 2010, 11:52 AM
Hi, I'm trying to make a square grid of circles (ex: 3x3, 5x5) using a for loop.
for(int i=1; i<=Lines; i++){
g.setColor (Color.RED);
g.fillOval(x+(SIZE*i/(Lines+1)),y+(SIZE/(Lines+1)),4,4);
}
This loop creates only a single row of circles. I'm at a loss as to how to modify this to create an entire grid of circles.
Any help is appreciated, thanks
TheGreatCthulhu
March 4th, 2010, 12:34 PM
You can use two loops, one inside the other.
If you still want to use only one:
For a grid of n x m fields (n rows, m columns), you'll have to draw n*m circles, so
int count = n*m;
You would loop from i=0 to i<count.
If (x1, y1) are the coordinates of each circle, and (x,y) is the starting point, then:
row = i / n (integer division)
and
column = i % m.
So,
x1 = x + SIZE * column;
y1 = y + SIZE * row; // if you are drawing bottoms-up, then y1 = y - SIZE * row.
keang
March 4th, 2010, 01:56 PM
Unless there is a compelling reason to do otherwise go with TheGreatCthulhu's first suggestion of 2 loops. It's easier to write, easier for someone else (or yourself after 'n' years) to read and understand and less prone to errors.
for(int x = 0; x < nCols; x++) {
for(int y = 0; y < nRows; y++) {
... your code here...
}
}
yzobel
March 4th, 2010, 05:11 PM
Thank you both very much!
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.