我在GridLayout中放了一堆按钮。如果我希望用户能够在运行时更改网格大小,我该如何生成新网格?我尝试重置行/列并重新添加按钮,但没有任何变化。
用于调整网格大小的cope代码段的后期编辑:
GridLayout layout = new GridLayout(10, 10);;
void makeGrid(int newSize) {
for(int i = 0; i <= gridSize; i++) {
for(int j = 0; j <= gridSize; j++) {
layout.removeLayoutComponent(grid[i][j]);
}
}
gridSize = newSize;
layout = new GridLayout(gridSize, gridSize);
panel.setLayout(layout);
for(int i = 0; i <= gridSize; i++) {
for(int j = 0; j <= gridSize; j++) {
panel.add(grid[i][j]);
}
}
pack();
}
答案 0 :(得分:0)
尝试定义一个单独的方法来显示按钮,如
// pane is your JPanel object
public void displayButtons(){
pane.add(btn1);
pane.add(btn2);
pane.add(btn3);
pane.add(btn4);
pane.add(btn5);
pane.add(btn6);
pack(); // <- make sure you include this code
}
然后从类监听器中设置一个新布局,然后调用displayButtons()方法。
pane.setLayout(new GridLayout(0,2));
displayButtons();