0

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?

1
  • 1
    JButton[][] buttons = JButton[3][3]; ? Commented Jun 30, 2014 at 20:58

2 Answers 2

3

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();
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Would be better to use < buttons.length and < buttons[i].length
Yep, as @MadProgrammer suggests, this will avoid magic numbers and improve safety.
I was getting error for writing in the loop - JButton buttons[i][x] = new JButton();
What error are you getting? It should not be JButton buttons[i][x], it should be buttons[i][x] = new JButton()
yes I'm just saying why i got the error earlier. Thanks to you its now resolved. (y)
1
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

@peeskillet Thanks for the observation, fixed.

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.