0

I have to make a java program which shows rows of squares using arrays.

Here is my code:

 @Override
    public void paint(Graphics g) 
    {
        for(int i=0;i<50;i++)

        {
             g.drawRect(x_coord,y_coord,cellWidth,cellHeight);

            x_coord =x_coord+cellWidth;
        }
    }

I need to have multiple rows of this. It must all be in one array so i can read each square using the array index.

2
  • 3
    It's unclear what it is you want. Does the array contain the cell x/y coordinate or some kind of value? Do you know the number of rows or columns? Commented Dec 29, 2019 at 20:56
  • improved formatting Commented Dec 30, 2019 at 5:59

1 Answer 1

0

It is not quite clear, what you want...

@Override public void
paint(Graphics g) 
{
  for(int col=0; i<*your colums*; ++i)
  {
    for(int row=0; i<*your rows*; ++i)
    {
      g.drawRect(cellWidth *col, cellHeight *row,
                 cellWidth, cellHeight);
    }
  }
}

To get the coordinate values:

cell y is cellWidth *column, cell x is cellHeight *row.

Another approach I can imagine is that every cell is an object

public class
Cell
{
  public static final int
  WIDTH= *your cell width*,
  HEIGHT= *your cell height*;

  public int
  x, y;

  public
  Cell(int col, int row)
  {
    x= col* WIDTH;
    y= row* HEIGHT;
  }

  public void
  draw(Graphics g)
  {
    g.drawRect(x, y, WIDTH, HEIGHT);
  }
}

usage:

initialize

int
COLUMNS= *your colums*,
ROWS= *your rows*;

Cell[]
cells=new Cell[COLUMNS][ROWS];

for(int col=0; i<COLUMNS; ++i)
{
  for(int row=0; i<ROWS; ++i)
  {
    cells[col][row]=new Cell(col, row);
  }
}

draw

@Override public void
paint(Graphics g) 
{
  for(Cell[] cell_col)
  {
    for(Cell cell : cell_col)
    {
      cell.draw(g);
    }
  }
}

To get the coordinate values:

cell x is cells[column][row].x, cell y is cell x is cells[column][row].y