Reputation: 1
I have to make a 2D array of JCheckBoxes
in Java. I'm using the code below, but when I try to set selected true:
checks[0][1].setSelected(true);
it says that checks[0][1]
is null
.
JCheckBox[][] checks = new JCheckBox[14][14];
for (int i = 0; i < 14; i++) {
for (int j = 0; j < 14; j++)
this.add(new JCheckBox(""));
Upvotes: 0
Views: 35
Reputation: 4213
You have to create each JCheckBox
in the array and then add it. I'd also suggest using named constants instead of magic numbers, like so:
final int NUM_BOXES = 14; // named constant
JCheckBox[][] checks = new JCheckBox[NUM_BOXES][NUM_BOXES];
for (int i = 0; i < NUM_BOXES; i++) {
for (int j = 0; j < NUM_BOXES; j++)
checks[i][j] = new JCheckBox("");
this.add(checks[i][j]);
}
}
Upvotes: 1