Java:NullPointerException初始化和填充2D数组对象甚至数组

时间:2014-01-10 11:26:34

标签: java arrays nullpointerexception

在方法forest()中,我创建了一个2D对象数组,然后填充它。我确信数组已填满,因为我可以在方法forest()中的类Forest中显示数组的内容,也可以在方法setTree()中的类Tree中显示数组的内容,如下所示。不幸的是,我无法通过showContentOfTree()或其他方法获取此内容。错误apears:NullPointerException

问题是它为什么会发生以及我应该改变什么?

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
    }
}

堆栈追踪:

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.main(Glowny.java:10)

1 个答案:

答案 0 :(得分:4)

tree方法中的forest变量为shadowing

public forest(){
        setLayout(null);
        loadImage = new LoadImage();
        loadImage.Image();
        tree = new Tree[16][16]; //<-- remove Tree[][]