In a method forest() I create a 2D array of objects then I fill it. I am sure that the array is filled because I can display the content of the array in class Forest in method forest() as well as in class Tree in method setTree() as shown below. Unfortunately, I can't get to this content by method showContentOfTree() or elsewhere. An error apears: NullPointerException
The question is why it happens and what I should change?
public class Forest extends JPanel {
private LoadImage loadImage;
private Tree[][] tree;
public forest(){
setLayout(null);
loadImage = new LoadImage();
loadImage.Image();
Tree[][] tree = new Tree[16][16];
for (int y = 0; y < 16; y++){
for (int x = 0; x < 16; x++){
tree[x][y] = new Tree();
tree[x][y].setTree(loadImage.loadForest(x,y));
System.out.println("Tree species " + tree[x][y].treeSpecies);
//here System displays loaded treeSpecies successfully
}
}
showContentOfTree();
}
public void showContentOfTree(){
for (int y = 0; y < 16; y++){
for (int x = 0; x < 16; x++){
System.out.println("Tree species" + tree[x][y].treeSpecies);
//here System DOES NOT displays loaded treeSpecies:
//Error apears: java.lang.NullPointerException
//at Forest.showContentOfTree(Forest.java:31)
}
}
}
public class Tree{
String treeSpecies;
public void setTree(String treeSpecies){
this.treeSpecies = treeSpecies;
System.out.println("Tree species " + treeSpecies);
//here System also displays loaded treeSpecies successfully
}
}
Stack trace:
Exception in thread "main" java.lang.NullPointerException at Forest.showContentOfTree(Forest.java:31)
at Forest.<init>(Forest.java:26)
at Okno.<init>(Okno.java:19)
at Glowny.main(Glowny.java:10)