Problem with array values
I'm trying to get java to draw 100 squares in a grid but it's not working properly. It compiles and runs without error but it only prints 1 square. Uncommenting the println() in makeGrid() shows the array is filled with the right values but the println() in paint() shows every entry is exactly the same (the last entry entered is repeated)
I have no idea how the values are changed or why.
Code java:
import java.awt.*;
import java.awt.event.*;
public class GridTest extends Canvas
{
private int squaresize;
private int[] grid = new int[100];
private Rectangle[] rects = new Rectangle[100];
private int offset = 25;
public Dimension getPreferredSize() {
return new Dimension(300,300);
}
public void makeGrid()
{
squaresize = 10;
for(int h=0;h<100;h++)
{
grid[h] = h;
for(int i=0;i<10;i++)
{
for(int j=0;j<100;j+=10)
{
this.rects[h] = new Rectangle(offset + j, offset + (i*10), squaresize, squaresize);
//System.out.println(rects[h].toString());
}
}
}
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
for(int i=0;i<rects.length;i++)
{
g2.draw(rects[i]);
//System.out.println(rects[i].toString());
}
}
public static void main(String[] args)
{
GridTest gt = new GridTest();
gt.makeGrid();
Frame f = new Frame("GridTestFrame");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(gt);
f.pack();
f.setVisible(true);
}
}
Re: Problem with array values
Did you look at the 100 lines of print outs?
Did it look like there were different rectangles?
What was the difference between one rectange and the next one?
Re: Problem with array values
Yes, like i said, the first println shows the proper x and y values on everything, the second one shows the same x and y value for everything (115)
Re: Problem with array values
Which is the first println? The one in makeGrid? How many lines does it print? Add a separate counter variable and print that with the rects value:
System.out.println("cntr=" + cntr++ + " " +rects[h].toString() + ", h=" + h);
Define cntr as an int outside of the loops.
The second println in the paint method shows that the contents of the array are all the same.
Look at how the index to the array changes as you are creating the elements and storing them in the array.
Re: Problem with array values
i changed it to:
Code java:
int h = 0;
for(int i=0;i<10;i++)
{
for(int j=0;j<100;j+=10)
{
rects[h] = new Rectangle(offset + j, offset + (i*10), squaresize, squaresize);
h++;
}
}
now it works! :) thanks for the help Norm
Re: Problem with array values
Yep. That looks like it'd work.