Your attempt at selecting exactly 20 buttons randomly is incorrect.
You have a multidimensional array in Java containing 100 JButtons, in a 10x10 grid like so:
buttons = [
[JButton0, JButton1, ..., JButton9],
...
[JButton89, JButton90, ..., JButton99]
]
And you want to select 20 buttons randomly. But in the code you provided, you are iterating over all the buttons, and inside the loop you are generating a random number and checking if this iteration matches the random number.
This is wrong, you should randomly select 20 unique indexes, and individually change the buttons at those random indexes.
Here's some code that will will selected 20 buttons by random from a multidimensional array.
JButton[][] buttons = new JButton[10][10]; // Array of 100 JButtons
int totalButtons = 0; // Length of total buttons
for (int i = 0; i < buttons.length; ++i) { // Count the length of total buttons
if (i == 0) {
totalButtons = buttons[i].length;
} else {
totalButtons += buttons[i].length;
}
}
int[] randomIndex = new int[20]; // 20 random button indexes
// Fill random indexes
Random random = new Random(); // Generate a random
for (int i = 0; i < randomIndex.length; ++i) { // Iterate over randomIndex array
int randomInt = random.nextInt(totalButtons); // Get a random integer from the random
for (int j = 0; j < i; ++j) { // Iterate over randomIndex array but no further than i
if (randomInt == randomIndex[j]) { // Check if random index already exists
randomInt = random.nextInt(totalButtons); // If random index already exists, select a different index
--j; // Do not iterate, check same index again
}
}
randomIndex[i] = randomInt; // Set random index
}
// Change button texts
for (int i : randomIndex) { // Iterate over random indexes
int row = i / 10; // Get row from index
int col = i % 10; // Get column from index
buttons[row][col].setText("treasure"); // Modify randomly selected button
}