|
-
March 4th, 2010, 12:52 PM
#1
Grid of circles
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
-
March 4th, 2010, 01:34 PM
#2
Re: Grid of circles
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.
-
March 4th, 2010, 02:56 PM
#3
Re: Grid of circles
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.
Code:
for(int x = 0; x < nCols; x++) {
for(int y = 0; y < nRows; y++) {
... your code here...
}
}
-
March 4th, 2010, 06:11 PM
#4
Re: Grid of circles
Thank you both very much!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|