1

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)

1
  • can you post a stack trace? Commented Jan 10, 2014 at 11:27

1 Answer 1

4

You are shadowing your tree variable in your forest method.

public forest(){
        setLayout(null);
        loadImage = new LoadImage();
        loadImage.Image();
        tree = new Tree[16][16]; //<-- remove Tree[][] 
2
  • you might say he cant see the forest for the trees ...I kill me Commented Jan 10, 2014 at 11:30
  • 2
    +1, very good catch, this can almost count as an exam question :), my eyes just skimmed right over it Commented Jan 10, 2014 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.