NullPointerException in a double loop
Hello fellow javanians,
Breaking my head over this method for the last 3 hours. I'm getting a NullPointerException in this double loop. I know it's coming from lblEmpty[row][col] in pnlBoard.add(lblEmpty[row][col]); because I changed it with a testlabel (one that wasn't created in the loop) and it worked...
Scenario: I have to get a predesigned gameboard from a DB (works because I first did it with a JTextPane and copied the displayBoard method from our working ConsoleApplication) and display it in my GUI. So I made a JPanel to house the gameboard and made a double loop to add JLabels according to the size of the gameboard in the DB.
Error comes from pnlBoard.add(lblEmpty[row][col]); where lblEmpty[row][col] doesn't seem to exist according to Java (and Java tends to be right a lot).
Here's my loop:
Code:
private JLabel lblEmpty[][];
private JPanel pnlBoard;
//loads of other, unrelated code
initGUI(){
// loads of other, unrelated code
getContentPane().add(displayBoard());
}
private JPanel displayBoard()
{
String[][] spelbord=domeinController.startSpel();
GridLayout grid = new GridLayout(spelbord.length, spelbord[0].length, 2, 2);
pnlBoard = new JPanel();
pnlBoard.setLayout(grid);
pnlBoard.setBounds(20,20,500,420);
lblEmpty = new JLabel[spelbord.length][spelbord[0].length];
for(int row=0;row<spelbord.length;row++)
{
for(int col=0;col<spelbord[row].length;col++)
{
if(row == spelbord.length -2 && col == spelbord.length -2){
lblFinish = new JLabel("FINISH");
pnlBoard.add(lblFinish);
}
else
lblEmpty[row][col] = new JLabel("X");
pnlBoard.add([COLOR="red"]lblEmpty[row][col][/COLOR]);
}
}
return pnlBoard;
}
As far as I can tell there's nothing wrong with this loop aside from not creating the lblEmpty ...
If you'd like more info, please feel free to ask.
Kind regards, Bloitz
PS: Dutch ==> English translations if its any help:
spelbord = gameboard
domeinController = domainController