【问题标题】:Draw rows of cells using array (Java)使用数组(Java)绘制单元格行
【发布时间】:2019-12-29 20:54:37
【问题描述】:

我必须制作一个使用数组显示正方形行的 java 程序。

这是我的代码:

 @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;
        }
    }

我需要多行这个。它必须全部在一个数组中,这样我就可以使用数组索引读取每个方块。

【问题讨论】:

  • 不清楚你想要什么。数组是否包含单元格 x/y 坐标或某种值?你知道行数或列数吗?
  • 改进格式

标签: java arrays graphics paint drawrect


【解决方案1】:

不太清楚,你想要什么……

@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);
    }
  }
}

获取坐标值:

单元格 y 是 cellWidth *column,单元格 x 是 cellHeight *row

我可以想象的另一种方法是每个单元格都是一个对象

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);
  }
}

用法:

初始化

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);
  }
}

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

获取坐标值:

单元格 x 是 cells[column][row].x,单元格 y 是单元格 x 是 cells[column][row].y

【讨论】:

    猜你喜欢
    • 2022-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2011-08-06
    • 2018-01-08
    • 2019-10-23
    • 1970-01-01
    相关资源
    最近更新 更多