[英]How do I make a new grid?
I'm putting a bunch of buttons into GridLayout. 我在GridLayout中放了一堆按钮。 If I want the user to be able to change the grid size during run time, how do I generate a new grid?
如果我希望用户能够在运行时更改网格大小,如何生成新的网格? I tried resetting the row/cols and re-adding the buttons, but nothing changes.
我尝试重置行/列并重新添加按钮,但是没有任何变化。
Late edit of cope snippet for resizing the grid: 后期编辑应付代码段以调整网格大小:
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();
}
try defining a separate method for displaying the buttons like, 尝试定义一个单独的方法来显示按钮,例如
// 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
}
Then from your class listener, set a new layout then call displayButtons() method. 然后从您的类侦听器中,设置一个新的布局,然后调用displayButtons()方法。
pane.setLayout(new GridLayout(0,2));
displayButtons();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.