我正在尝试使用FormLayout
创建网格,但它似乎将每个新元素显示在其他元素之上。我想问题出在CellContraints
和FormLayout
上。请注意,CityPanel
扩展了Panel
。
public class MapPanel extends JPanel {
public MapPanel() {
drawMap(5, 5);
}
private void drawMap(columns, rows) {
ColumnSpec[] columnSpec = new ColumnSpec[columns];
for(int i = 0; i < columns; i++)
columnSpec[i] = FormSpecs.DEFAULT_COLSPEC;
RowSpec[] rowSpec = new RowSpec[rows];
for(int i = 0; i < rows; i++)
rowSpec[i] = FormSpecs.DEFAULT_ROWSPEC;
FormLayout layout = new FormLayout(columnSpec, rowSpec);
this.setLayout(layout);
CellConstraints cc = new CellConstraints(columns, rows);
//draw the grid
for (City city : gameMap.getCities().values()) {
Dimension dimension = new Dimension(100, 100);
CityPanel cityPanel = new CityPanel(city, dimension);
//this code put the cityPanel in a cell. It's confirmed by the println()
this.add(cityPanel, cc.xy(mapGrid.getColumn(city), mapGrid.getRow(city), CellConstraints.CENTER, CellConstraints.CENTER));
System.out.println(city.getName() + " -> (" + mapGrid.getColumn(city) + "," + mapGrid.getRow(city) + ")" );
}
}
}