This site requires JavaScript, please enable it in your browser!
Greenfoot back
-nic-
-nic- wrote ...

2013/1/30

Creating an object creates a null pointer exception?

-nic- -nic-

2013/1/30

#
public void feel(int i){  
      if(Greenfoot.mousePressed(this)){
        getWorld().removeObjects(getWorld().getObjects(null));
        switch(i)
          {
            case 0: Opt(); break;
            case 1: Play();break;
            case 2: Info();break;
            }
      }
    }
    public void Opt()
    {
       Info info = new Info();
       getWorld().addObject(info, 471, 324);
    }
    public void Play(){}
    public void Info(){}
When the line is called to add the object info that is when the error is created There is only the act method on the info class so far
vonmeth vonmeth

2013/1/30

#
You are removing all objects from the world (including what ever object is calling this), and then using getWorld, which is going to return null because the object has been removed from the world. You could try having a constant reference to the world (maybe create the reference with the addedToWorld method).
danpost danpost

2013/1/30

#
Or just get the reference right there before removing all the objects.
public void feel(int i){  
      if(Greenfoot.mousePressed(this)){
        World world = getWorld();
        world.removeObjects(world.getObjects(null));
        switch(i)
          {
            case 0: Opt(world); break;
            case 1: Play();break;
            case 2: Info();break;
            }
      }
    }
    public void Opt(World world)
    {
       Info info = new Info();
       world.addObject(info, 471, 324);
    }
    public void Play(){}
    public void Info(){}
-nic- -nic-

2013/1/30

#
Thanks Danpost and Vonmeth
You need to login to post a reply.