Seeker
Seeker

Reputation: 509

making 3 by 3, 2d array in java

Hi I was just working with arrays and I had few problems with creating a 2D array in a 3 by 3 grid.

Below is an example of 1D arrray that I created with 9 buttons which is working fine atm, as it displays all 9 of the buttons.

    frame.setLayout(new GridLayout(3,3));
    JButton[] buttons = new JButton[9];

    for (int i = 0; i < buttons.length; i++){
        buttons[i] = new JButton();
        frame.add(buttons[i]);
        buttons[i].setText(".");

However, when I try doing this with 2D array only 6 out of 12 buttons show up.

    frame.setLayout(new GridLayout(3,3));
            JButton[][] buttons = new JButton[3][3];
    for (int i = 0; i < buttons.length; i++){
        for (int j = 0; j < buttons.length; j++){
        buttons[i][j] = new JButton();
        frame.add(buttons[i][j]);
        buttons[i][j].setText(".");

        }
    }

Also, I have one more question, to call each individual button do I need to do it like this?

button[0].setText("button 1");

and also would it be possible to give each button a name, for example instead of button[0], would it be possible to have button1, and so on.

Thanks.

Upvotes: 1

Views: 2662

Answers (2)

FazoM
FazoM

Reputation: 4956

You have a bug here:

for (int j = 0; j < buttons.length; i++){

should be:

for (int j = 0; j < buttons.length; j++){

For your other questions:

Yes, you need to invoke button[...].setText("..."); for each button to assign it's name. (you can incorporate your loop indexes to automate this).

and also would it be possible to give each button a name, for example instead of button[0], would it be possible to have button1, and so on.

That's why you created an array to avoid dealing with multiple object button1, button2, etc. This is because now you can process them in a loop.

EDIT: also there is a problem with your array init:

JButton[] buttons = new JButton[12];

This creates a 1-dimension array. What you want is something like:

JButton[][] buttons = new JButton[3][3]; //[3][4] ?

EDIT2:

int number = 0;
for (int i = 0; i < buttons.length; i++){
    for (int j = 0; j < buttons[0].length; j++){  //watch here for additional index [0] in length (it is size of "second dimension")
        buttons[i][j] = new JButton();
        frame.add(buttons[i][j]);
        buttons[i][j].setText("Button" + number);
        number++; //in separate line for clarity
    }
}

Upvotes: 3

Embattled Swag
Embattled Swag

Reputation: 1469

Your second for loop has for (int j = 0; j < buttons.length; i++)...it should be j++, not i++.

Also, like turbo pointed out, a 3x3 grid isn't large enough to hold 12 buttons (I'm assuming you mean 4x3 or 3x4?). Also, instead of comparing both i and j to buttons.length, you should probably have two separate variables to compare each against (buttonsWidth, buttonsLength; buttonsX, buttonsY, etc.).

Upvotes: 6

Related Questions