在 Java 中将 20 个随机宝藏插入 10 x 10 的网格中

Inserting 20 random treasures into a 10 x 10 grid in Java

我创建了一个 GUI,大小为 10 x 10,有 100 个按钮。我必须插入 20 个宝物,让其他 80 个空着。这是我使用的代码。有时我得到 17 个宝藏,有时是 18 个,有时是 19 个。我该如何解决这个问题?

提前致谢。

Random random = new Random();
        for (int index = 0; index < 20; index++)
        {
            int insertionIndex = random.nextInt(99)+1;
            buttonGrid[insertionIndex] = new TreasureButton(treasureGame, this);
        }
        // Loop to add EmptyButton()'s into remaining null indexes within the buttonGrid
        for (int index = 0; index < 100; index++)
        {
            // if the current index is null, add an EmptyButton() into it
            if (buttonGrid[index] == null)
            {
                buttonGrid[index] = new EmptyButton(treasureGame, this);
            }
        }
        // Loop to add all of the contents of the buttonGrid into the gamePanel
        for (int index = 0; index < 100; index++)
        {
            gridPanel.add(buttonGrid[index]);
        }
  1. 创建一个 ArrayList
  2. 将 20 个 TreasureButton 实例添加到 ArrayList
  3. 向 ArrayList 添加 80 个 EmptyButton 实例
  4. 使用 Collections.shuffle(...) 随机化按钮。
  5. 遍历 ArrayList 并将每个按钮添加到面板