1

I am assigning several buttons to a gridpane. Each button has a number as its text. I created an arrayList numbers and add numbers to it. I use collections to shuffle the numbers (I want to have a random number in each button everytime I run the program). Then I add a number to each button text using this arrayList.

I want each button to have a different number. However, right now each button in 1 column have the same number.

Any suggestions on how to fix this issue will be greatly appreciated (random assignment of the text of button).

This is my code:

Button[][] b= new Button[2][2];
List<Integer> n = new ArrayList<>();

    for(int i=0; i <2; i++){
        for(int j=0; j <2; j++){
            b[i][j] = new Button(String.valueOf(n.get(i)));
            pane.add(button[i][j], i, j);
        }
    }

1 Answer 1

1

With numbers.get(i) you are only accessing the first 4 numbers in your ArrayList, since i iterates from 0 to 3.

Change

b[i][j] = new Button(String.valueOf(numbers.get(i)));

to

b[i][j] = new Button(String.valueOf(n.get(i*4+j)));

Edit :

Note that you should use the n ArrayList, Not numbers (which I have no idea what it contains).

Sign up to request clarification or add additional context in comments.

1 Comment

It works I had an error when I typed it in my code. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.