user3325350
user3325350

Reputation: 11

How to randomly choose a button from a 2d array of buttons in java?

I have made 2d array of JButtons

public JButton[][] buttons = new JButton[5][5];

and have created a for loop to make those buttons 25 times

for(int i = 0; i < 5; i++) {
    for(int j = 0; j < 5; j++) {
     buttons[i][j] = new JButton();
        panel.add(buttons[i][j]);

            }
        }
    }

now what I want to do is select a button randomly from those created above and set its text to what I define, I have attempted it like this, but it is not working, it only selects from 3 of the buttons and not the rest.

int r = (int) (Math.random());
buttons[r][r].setText(button[random][random].getName());

So basically, I want a random button to be selected from the array and its value to be changed to its name. Also, how can I print out the name of the button in string currently when I print the name it prints out random stuff.

Thanks.

Upvotes: 0

Views: 1108

Answers (2)

indivisible
indivisible

Reputation: 5012

You need to select a random array and then a random index to ensure you don't go outside the bounds of any in the individual arrays.

//create buttons first
Random random = new Random();
JButton[] buttons randomButtonsArray = buttons[random.nextInt(buttons.length)];
JButton randomButton = randomButtonsArray[random.nextInt(randomButtonArray.length)];

Upvotes: 1

user2864740
user2864740

Reputation: 61885

The expression (int) (Math.random()) always evaluates to 0 because Math.random() returns a double in the range [0, 1) - such a double will always result in 0 when cast to an integer.

Instead, create a new Random object and use Random.nextInt(n) to choose an appropriate value in the range. For example,

Random r = new Random();
int i = r.nextInt(5); // chooses 0, 1, .. 4
int j = r.nextInt(5);

JButton b = buttons[i][j];
b.setText(b.getName());

(But you probably don't want Component.getName()..)

Upvotes: 3

Related Questions