如何在 Java 中的 GridLayout 面板的特定单元格中添加标签?

How can I add labels in specific cells of a GridLayout Panel in Java?

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();

        ImageIcon grassIcon = new ImageIcon("C:\Users\Pamvotis\Desktop\Project\img\icon.png"); 
        JLabel labels = new JLabel();

        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 6; col++) {
                gbc.gridx = col;
                gbc.gridy = row;

                CellPane cellPane = new CellPane();
                Border border = null;
                if (row < 9) {
                    if (col < 5) {
                        border = new MatteBorder(1, 1, 0, 0, Color.BLACK);
                    } else {
                        border = new MatteBorder(1, 1, 0, 1, Color.BLACK);
                    }
                } else {
                    if (col < 5) {
                        border = new MatteBorder(1, 1, 1, 0, Color.BLACK);
                    } else {
                        border = new MatteBorder(1, 1, 1, 1, Color.BLACK);
                    }
                }
                cellPane.setBorder(border);
                if ((row==0)&&((col==2)||(col==3))) { 
                    cellPane.setBackground(Color.RED);
                } else if ((row==9)&&((col==2)||(col==3))) { 
                    cellPane.setBackground(Color.WHITE);
                    labels = new JLabel(grassIcon);add(labels);
                } else {
                    cellPane.setBackground(Color.GREEN);
                }

                add(cellPane, gbc);
            }
        }
    }

所以我有这段代码,但问题是每次我 运行 程序时,带有图像的标签都放在网格之后的第一行。它发生在我让标签总是出现在网格的第一行或网格之后的第一行的所有其他尝试中。谁能帮我解决这个问题?

add(labels);

您正试图在未指定约束的情况下将标签添加到面板。我相信将使用默认约束(无论它们是什么)。

如果您想控制组件的位置,那么您需要在每个 add(...) 语句中指定约束。

编辑:

else if ((row==9)&&((col==2)||(col==3))) {cellPane.setBackground(Color.WHITE);labels = new JLabel(grassIcon);add(labels);}

我猜你想要:

else if ((row==9)&&((col==2)||(col==3))) 
{
    cellPane.setBackground(Color.WHITE);
    labels = new JLabel(grassIcon);
    //add(labels);
    cellPane.add(labels);
}
else 

现在您只需确保 "cellPane" 使用布局管理器。