gpt4 book ai didi

java - 在 Java 中为 GridLayout 创建单元格

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:53 25 4
gpt4 key购买 nike

我正在尝试用 java 为我的蛇梯游戏创建一个网格,但是我有一个小问题,我创建的网格中有不需要的空间

enter image description here

有谁知道我怎样才能摆脱它?

这是我为客户端 (Client.java) 编写的代码:

//Initialize Grid Cells
private Cell[][] cell = new Cell[10][10];

//Create Grid Layout
GridLayout GameBoard = new GridLayout(10, 10, 1, 1); //Create GridLayout
GameArea.setLayout(GameBoard); //Add GridLayout
GameArea.setPreferredSize(new Dimension(590,560));
GameArea.setOpaque(false);

//Add Cells to Grid
for (int v = 0; v < 10; v++)
for (int h = 0; h < 10; h++)
GameArea.add(cell[v][h] = new Cell(v, h, this));

//Individual Image on Each Cell
cell[1][0].add(new JLabel(GreenGrid));

这是我为单元格 (Cells.java) 编写的代码,它还扩展了 JPanel:

//Indicate the row and column of this cell in the board
private int GridRow;
private int GridColumn;

private Client parent;

public Cell(int GridRow, int GridColumn, Client GUI) {

this.GridRow = GridRow;
this.GridColumn = GridColumn;
this.parent = GUI;

setBorder(new LineBorder(Color.orange, 1)); // Set cell's border
setBackground(Color.gray);

}

最佳答案

我看不到你的图片,但我怀疑你的布局有问题。顺便说一句,您的 Cell 扩展了 JPanel 吗?您是设置其布局管理器还是使用默认的 FlowLayout?

考虑:

  • 您不应在 GameBoard 上调用 setPreferredSize(...),因为这会决定您的网格单元格大小,这太大了。
  • 相反,细胞本身应该决定自身和整个网格的大小。
  • 考虑让 Cell 覆盖 getPreferredSize() 并返回 JLabel 图像的尺寸(如果存在的话),或者返回 super 的结果。
  • 请务必在添加所有组件之后并在将其设置为可见之前在顶层窗口上调用 pack()
  • 考虑让 Cell 使用 BorderLayout 并将您的 JLabel 添加到 BorderLayout.CENTER 位置,以便它填充单元格(如果这是您想要的)。

要获得更多帮助和更好的帮助,请考虑创建并发布 sscce .

关于java - 在 Java 中为 GridLayout 创建单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20646015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com