编程语言
首页 > 编程语言> > 在Java中为GridLayout创建单元格

在Java中为GridLayout创建单元格

作者:互联网

我正在尝试为Java中的蛇和梯子游戏创建网格,但是我有一个小问题,即我创建的网格中有多余的空间

有谁知道我能摆脱它吗?

这是我为客户端(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(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);

} 

解决方法:

您的第一个问题在这里…

GridLayout GameBoard = new GridLayout(10, 10, 1, 1); //Create GridLayout

如JavaDocs中所述…

public GridLayout(int rows,
int cols,
int hgap,
int vgap)

Creates a grid layout with the specified number of rows and columns.
All components in the layout are given equal size.

In addition, the horizontal and vertical gaps are set to the specified
values. Horizontal gaps are placed between each of the columns.
Vertical gaps are placed between each of the rows.

One, but not both, of rows and cols can be zero, which means that any
number of objects can be placed in a row or in a column.

这意味着,您通过向hgap和vgap参数提供非零值来提供间隔.

如果您使用类似…

GridLayout GameBoard = new GridLayout(10, 10); //Create GridLayout             

你最终会得到类似…

如前所述,我将避免使用GameArea.setPreferredSize(new Dimension(590,560));而是重写Cell类的getPreferredSize方法.由于GridLayout的工作方式,这不会停止调整单元格的大小,但是无论如何这可能是理想的…

标签:grid-layout,layout,grid,java
来源: https://codeday.me/bug/20191122/2059060.html