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

标签 java swing jpanel layout-manager grid-layout

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”使用布局管理器。

关于java - 如何在 Java 中的 GridLayout 面板的特定单元格中添加标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36797013/

相关文章:

java - 有没有一种简单的方法可以从显示的 JFreeChart 图表中删除 TimeSeries?

java - 使用 jcombobox 在 java 中过滤国家/地区-州-城市代码

java - 如何持续更新JPanel?

java - 将图像添加到 Android Studio 1.3.1 项目

java - 通过鼠标单击选择时,Wicket 自动完成文本字段不会更新模型

java - 如何获得由整数的某些数字组成的最大数字

java - RestTemplate:不热心的&符号编码

java - 如何在来自两个不同类的 JFrame 中将两个圆圈一起移动

Java setBackground() 混淆

java - 使用 BoxLayout 时 JPanel 不居中