swing如何在Java中的GridLayout面板的特定单元格中添加标签?
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);
}
}
}
我有这段代码,但问题是每次我运行程序时,带有图像的标签都放在网格后的第一行。每次尝试都会出现这种情况,我使标签始终显示在网格的第一行或网格后的第一行。有人能帮我吗
# 1 楼答案
您试图在不指定约束的情况下将标签添加到配电盘。我相信会使用默认约束(不管它们是什么)
如果要控制零部件的位置,则需要在每次添加时指定约束(…)声明
编辑:
我猜你想要:
现在您只需要确保“cellPane”使用布局管理器