English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have a question about a 2-D array of buttons.

I defined 9 buttons and I defined a 2-D array of buttons and I put these 9 buttons to the 2-D array of button;

JButton [] [] Buttons = {{button1, button2, button3},

{button4, button5, button6},

{button7, button8, button9}};


And now I can change the text of button1 in this way:

Button1.setText (“some thing”);

But I can not change it in this way:


for(int i=0 ; i<3 ; i++){

if (Board[i][0]+Board[i][1]==8 && Board[i][2]==0){

Board[i][2] = 4;

Buttons[i] [2].setText("O");

return;

}

}

Why? And what should I do if I want to change the button’s text through the array ?

2007-08-24 00:58:39 · 2 answers · asked by shayan k 1 in Computers & Internet Programming & Design

2 answers

It would be helpful if you'd indicate what the problem is. I'm assuming it is a NullPointerException.

If Buttons is a instance variable of your class, what is happening is this: the initialization happens right a the top of your constructor method, and the values of button1, button2, etc., are all null at that time.

To avoid this issue, instead do this: In the method where you initialize all the buttons, AFTER they are all created, construct the array with this code:

JButton [] [] Buttons = new Button[][] {{button1, button2, button3},
{button4, button5, button6},
{button7, button8, button9}};

The explicit "new Button[][]" constructor will cause the array to be constructed at that point, when you are sure that all the button values are set properly.

2007-08-24 01:26:43 · answer #1 · answered by McFate 7 · 0 0

basically a 2d array is a collection of arrays which contains items. if you want to access button1 do this:

Buttons[0][0].setText("some thing");

by doing this you refer to first element of the first array contained in the Buttons. hope this helps. where:

Buttons[int arrayIndex][int elementOfArray];

maybe you have some problems with your array indexes.

hope this helps.

2007-08-24 09:45:34 · answer #2 · answered by rodette p 3 · 0 0

fedest.com, questions and answers