将 JLabel 的二维数组打印到 GridLayout

Printing a 2D array of JLabels to a GridLayout

我有一个迷宫创建程序,想把它放到图形用户界面中。我的迷宫位于一个二维数组中,因此我计划在 JPanel 中创建一个二维 JLabel 数组,并根据每个标签是路径还是墙为其分配颜色。我可以创建 JLabel 的二维数组并将其添加到我的面板中,但是当我 运行 它时,所有 JLabel 都向右移动一个 space 所以我的左上角有一个空白 space并且比预期的多了一列,少了一行。

GUI 图片:

这是我的代码;我不确定是什么问题。我试过改变 GridLayout 的大小,改变我的循环次数 运行,改变 row 和 col 的值(现在都是 10),并尝试在那个地方手动创建一个额外的 JLabel,但是没有骰子。

public Maze() {
    JPanel panel = new JPanel();
    getContentPane().add(panel);

    int row = MazeCreator.r;
    int col = MazeCreator.c;

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 500, 500);
    getContentPane().setLayout(new GridLayout(row, col));

    JLabel[][] grid= new JLabel[row][col];
    for (int i = 0; i < row; i++){
        for (int j = 0; j < col; j++){
            grid[i][j] = new JLabel();
            grid[i][j].setBorder(new LineBorder(Color.BLACK));
            //grid[i][j].setBackground(Color.black);
            grid[i][j].setOpaque(true);
            super.add(grid[i][j]);
        }
    }
    grid[0][0].setBackground(Color.red);
}

我可以 "fix" 通过从 col 中减去 1 并将 1 添加到 row 来解决行太少和 cols 太多的问题,但这只会创建 99 个 JLabel 而不是 100 个,就像我说的那样,手动放置左上角的 JLabel 不起作用。

不要使用 super.add() 将标签添加到面板。并将面板的布局设置为 GridLayout 而不是 JFrame

public Maze() {
    JPanel panel = new JPanel();
    getContentPane().add(panel);

    int row = MazeCreator.r;
    int col = MazeCreator.c;

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 500, 500);
    panel.setLayout(new GridLayout(row, col));

    JLabel[][] grid= new JLabel[row][col];
    for (int i = 0; i < row; i++){
        for (int j = 0; j < col; j++){
            grid[i][j] = new JLabel();
            grid[i][j].setBorder(new LineBorder(Color.BLACK));
            //grid[i][j].setBackground(Color.black);
            grid[i][j].setOpaque(true);
            panel.add(grid[i][j]);
        }
    }
    grid[0][0].setBackground(Color.red);
}

您的代码结构令人困惑。

super.add(....);

使代码复杂化。为什么要使用 super(...)?您专门为标签创建一个面板,以将标签直接添加到面板中。不要使用 super.

通过显式创建游戏面板然后将组件添加到该面板来简化逻辑:

JPanel gamePanel = new JPanel( new GridLayout(...) );

for (...)
{
    JLabel label = new JLabel(...);
    gamePanel.add( label );
}

add( gamePanel ); // add our game panel to the content pane of the frame.

现在您的代码更加明确且不易出错。