How to initialize/declare a 2D array of reference type in Java? In particular I want to initialize a 2d array of JButton type (3x3) and then add them to a frame inside the constructor. How do i go about it?
2 Answers
MadProgrammer is correct, but in order to use them, you will need to initialize every JButton individually thereafter.
JButton[][] buttons = new JButton[3][3];
for(int i = 0; i <= 2; i++){
for(int x = 0; x <= 2; x++){
buttons[i][x] = new JButton();
}
}
5 Comments
MadProgrammer
Would be better to use < buttons.length and < buttons[i].length
Hovercraft Full Of Eels
Yep, as @MadProgrammer suggests, this will avoid magic numbers and improve safety.
Anurag
I was getting error for writing in the loop - JButton buttons[i][x] = new JButton();
George Daniel
What error are you getting? It should not be JButton buttons[i][x], it should be buttons[i][x] = new JButton()
Anurag
yes I'm just saying why i got the error earlier. Thanks to you its now resolved. (y)
JButton[][] myButtons = JButton[3][3];
creates the array you need. It declares and initializes the array. If you want to declare and initialize it separately, then you can do it this way:
JButton[][] myButtons;
//...
myButtons = JButton[3][3];
1 Comment
Lajos Arpad
@peeskillet Thanks for the observation, fixed.