簡體   English   中英

Java - 使用JButton根據數組中的索引填充網格布局

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM