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

2013/8/19

help pls!!

mattjames mattjames

2013/8/19

#
Need some help pls! whenever I click on the modify button it removes everything fine however gives me a null pointer exception on the indicated line. Please can someone explain how to fix it.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class modifybutton here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class modifybutton extends buttons
{
    public int traction=0;
    public int baysize=0;
    /**
     * Act - do whatever the modifybutton wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
       
        if (Greenfoot.mouseClicked(this))
        {
            
        
        getWorld().removeObjects(getWorld().getObjects(playbutton.class));

        getWorld().removeObjects(getWorld().getObjects(exitbutton.class));
        getWorld().removeObjects(getWorld().getObjects(modifybutton.class));

        getWorld().setBackground(new GreenfootImage("modification background.fw.png"));  //this line then comes up with a nullpointerexception 
        getWorld().addObject(new skisbutton(), 3 , 2);
        getWorld().addObject(new tracksbutton(), 5 , 2);
        getWorld().addObject(new wheelsbutton(), 7 , 2);
        getWorld().addObject(new largebaybutton(), 7 , 3);
        getWorld().addObject(new mediumbaybutton(), 5 , 3);
        getWorld().addObject(new smallbaybutton(), 3 , 3);
        getWorld().addObject(new backbutton(), 8 , 7);
    }
}
}
Gevater_Tod4711 Gevater_Tod4711

2013/8/19

#
The problem is that you remove all modifybutton objects in line 27. Because the class where this code is put into is a mudifybutton object it is removed from the world. After removing it from the world you call getWorld() which then returns null because your object is no longer in the world. So getWorld().setBackground(...) throws a NullPointerException because getWorld() returns null. To fix this problem you should first add all the object and then remove the modifybutton objects. So if you put line 27 of the code at the end of your code (after line 36) it should work.
mattjames mattjames

2013/8/19

#
Ah okay thanks
mattjames mattjames

2013/8/19

#
Worked perfectly thanks
You need to login to post a reply.