有没有办法创建一个带索引的数组,这样我就可以使用网格布局在我需要的这些索引中快速创建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个或高指数。
答案 0 :(得分:0)
你可以创建一个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];
}
}