简体   繁体   中英

Java - Filling a grid layout with JButtons based on indexes in an array

Is there a way to create an array with indexes so that I can use a grid layout to quickly create Jbuttons in only these indexes that I need. I'm making a game board for a project and I'm trying to do this as painlessly as possible and GUI is not my strongest feature.

// 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];
    }
   }

This code I had found was about a minesweeper game and actually puts mines in but I'm not sure this applies the same concept. To make it a little more understandable what I mean is that for example I want to make a 25x25 grid layout and I don't want to make JButtons for indexes (5,2),(7,6),(24,25), is there anyway to exclude these buttons? Or would it just be easier to manually remove them.

For my application of this process I will need more than 3 indexes excluded so if you choose to answer please think about it on a larger scale, around 25 or high indexes.

You could create an array of type Point and add the coordinates of the points you want to leave out.

Then before adding the mine, just check that the square in question is not one of those points you want to leave out

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];

    }   
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM