有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建多个相邻的1个对象(类似网格)

嘿,如果我有一个简单的矩形类,我怎样才能使它以类似网格的模式创建相邻的矩形?也许10行10列

public class Vak {

private int posX = 0;
private int posY = 0;
private int width = 50;
private int height = 50;
private Color colour;


public Vak(Color c, int x, int y){
    this.colour = c;
    this.posX = x;
    this.posY = y;

}

public int vakPosY(){
    return this.posY;
}
public int vakPosX(){
    return this.posX;
}

public void draw (Graphics g){
    g.setColor(this.colour);

    g.drawRect(posX, posY, width, height);
}

public void move(int numberPixelsX, int numberPixelsY){
    this.posX = this.posX + numberPixelsX;
    this.posY = this.posY + numberPixelsY;
}

}

这是我的矩形“vak”代码


共 (1) 个答案

  1. # 1 楼答案

    这就是你要找的吗

    int mapWidth = 10;
    int mapHeight = 10;
    // tileWidth and tileHeight should probably be public static const fields or static readonly properties of some class, but I put them here for now.
    int tileWidth = 50;  // Pixels
    int tileHeight = 50;  // Pixels
    // tiles should probably be a field of a Map class (if you have one)
    Vak[][] tiles = new Vak[mapWidth][mapHeight];
    for(int x = 0; x < mapWidth; x++)
    {
        for(int y = 0; y < mapHeight; y++)
        {
            tiles[x][y] = new Vak(Color.white, x*tileWidth, y*tileHeight);
        }
    }
    

    然后在主回路的绘图部分:

    for(Vak[] row : tiles)
    {
        for(Vak tile : row)
        {
            tile.draw(g);
        }
    }