[英]Java - Filling a grid layout with JButtons based on indexes in an array
有没有办法创建一个索引数组,以便我可以使用网格布局快速创建我需要的索引中的Jbuttons。 我正在为一个项目制作一个游戏板,我试图尽可能轻松地做到这一点,GUI不是我最强大的功能。
// Set the height to the number of rows, length to number of columns
setLayout(new GridLayout(mineGrid.length, mineGrid[0].length);
// For each row
for (int rowIndex = 0; rowIndex < mineGrid.length; rowIndex++) {
// For each column
for (int colIndex = 0; colIndex < mineGrid[0].length; colIndex++) {
// Add the button, because of GridLayout it starts @ the top row, goes across left to right, down a row, across left to right, etc.
add(mineGrid[rowIndex][colIndex];
}
}
我发现的这个代码是关于一个扫雷游戏,并且实际上放了地雷,但我不确定这适用于相同的概念。 为了使它更容易理解我的意思是,例如我想制作25x25网格布局,我不想为索引制作JButton(5,2),(7,6),(24,25) ,无论如何要排除这些按钮? 或者手动删除它们会更容易。
对于我的这个过程的应用,我将需要排除3个以上的索引,所以如果你选择回答,请考虑更大规模,大约25或高指数。
您可以创建一个Point类型的数组,并添加您想要忽略的点的坐标。
然后在添加矿井之前,只需检查所讨论的方块是否是您想要遗漏的那个点之一
Point[] exclude = new Point[numPointsToExclude];
//Here you would determine what are the points you want to exclude and add them to the array in the starting top row, goes across left to right, down a row, across left to right, etc.
int i = 0;
// Set the height to the number of rows, length to number of columns
setLayout(new GridLayout(mineGrid.length, mineGrid[0].length);
// For each row
for (int rowIndex = 0; rowIndex < mineGrid.length; rowIndex++) {
// For each column
for (int colIndex = 0; colIndex < mineGrid[0].length; colIndex++) {
// Add the button, because of GridLayout it starts @ the top row, goes across left to right, down a row, across left to right, etc.
if (new Point(colIndex, rowIndex).equals(exclude[i]) {
i++;
continue;
}
add(mineGrid[rowIndex][colIndex];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.