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

2016/11/21

nullPointerException

Nosson1459 Nosson1459

2016/11/21

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Controls here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Controls extends Actor
{
    private GreenfootImage image1=new GreenfootImage("MenuButtonControls.png");
    private GreenfootImage image2=new GreenfootImage("MenuButtonControlsOutline.png");
    public Controls()
    {
        setImage(image1);
    }
    /**
     * Act - do whatever the Controls wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        changeImage();
    }  
    private void changeImage()
    {
        Menu menu=(Menu)getWorld();
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(mouse.getX()>getX()-150&&mouse.getX()<getX()+150&&mouse.getY()<getY()+75&&mouse.getY()>getY()-75)
        {
            setImage(image2);
        }
        else
        {
            setImage(image1);
        }
    }
}
this passes as nullPointerException, y and how do i fix it
danpost danpost

2016/11/21

#
If no mouse actions are detected on any act cycle, then a 'null' value is returned by 'getMouseInfo'. You need to add the following line between lines 28 and 29:
if (mouse == null) return;
first, so you do not get the error; and second, so that the image is not changed if no mouse action was detected.
Nosson1459 Nosson1459

2016/11/22

#
thnx but wat does that return do, not that i dont think i need it but wat does it tell the computer to do
danpost danpost

2016/11/22

#
Nosson1459 wrote...
thnx but wat does that return do, not that i dont think i need it but wat does it tell the computer to do
The 'return' statement causes an immediate branch back out of the method back to the statement after where the method was called from. In your case, you do not want the method to do anything if the mouse is not moved. I could have said to place the check in with the other conditions in your 'if' statement:
if (mouse != null && mouse.getX()>getX()-150&&mouse.getX()<getX()+150&&mouse.getY()<getY()+75&&mouse.getY()>getY()-75)
but then, the image will change to 'image1' if the mouse did not move. That would not be something you would want to happen if the mouse is currently within the given rectangle.
Nosson1459 Nosson1459

2016/11/22

#
thnx
You need to login to post a reply.