메소드 forest()에서 객체의 2D 배열을 작성한 다음 채 웁니다. 클래스 포리스트의 메서드 포리스트()뿐만 아니라 아래 그림과 같이 메서드 setTree()의 Tree 트리에서 배열의 내용을 표시 할 수 있기 때문에 배열이 채워 졌으므로 확신합니다. 불행히도, 나는 showContentOfTree() 메소드 또는 다른 곳에서이 콘텐트를 볼 수 없다. 오류가 발생합니다. NullPointerExceptionJava : NullPointerException 객체 배열의 2D 배열도 초기화되고 채워짐
질문은 왜 발생하며 무엇을 변경해야합니까?
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
}
}
스택 추적 : Glowny.main에서
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)
(Glowny.java:10)
스택 추적을 게시 할 수 있습니까? –