I have a very simple constructor where I initialise a 2D array of type BooleanProperty to all false. However, I am getting a NullPointerException at the line grid[i][j].set(false)
. I am not sure why this is the case, as grid
is not null? I think I must be using BooleanProperty incorrectly, but I'm not sure why.
public class Game {
private BooleanProperty[][] grid;
public Game() {
grid = new BooleanProperty[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
grid[i][j].set(false);
}
}
}
// other methods
}
Answer
Even though you have created the array of BooleanProperty
references, you need to initialize each one. Try this:
public class Game {
private BooleanProperty[][] grid;
public Game() {
grid = new BooleanProperty[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
BooleanProperty p = new SimpleBooleanProperty();
p.set(false);
grid[i][j] = p;
}
}
}
// other methods
}
No comments:
Post a Comment