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

2011/11/24

java.lang.NullPointerException

darkmist255 darkmist255

2011/11/24

#
So, I'm getting a NullPointerException whenever I try to run this scenario. It says the problem lies at:
        MouseInfo mouse = Greenfoot.getMouseInfo();
        mouseXcalc = mouse.getX();
        mouseYcalc = mouse.getY();
It doesn't like "mouseXcalc = mouse.getX();" and probably won't like the next one either. I've used almost identical code in another method (just the mouseXcalc variable was different) and it works fine. What's my problem here? I can post more of the code if needed, this is just the problem part.
AwesomeNameGuy AwesomeNameGuy

2011/11/24

#
I'm not sure how getMouseInfo works but if you put it in an if block like this: if ( Greenfoot.mouseMoved(null)) {MouseInfo mouse = Greenfoot.getMouseInfo() } it will work. Might want to check and see if I got the name of the mouseMoved method right I'm typing this from memory. Anyway my theory is that getMouseInfo returns null unless the mouse has just done something. So that's where your null pointer exception could be coming from.
mjrb4 mjrb4

2011/11/24

#
getMouseInfo() will return null whenever the mouse information hasn't changed (i.e. the most has stayed in the same place.) So you need to check for this like so:
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null) {
    mouseXcalc = mouse.getX();
    mouseYcalc = mouse.getY();
}
davmac davmac

2011/11/24

#
Greenfoot.getMouseInfo() can return null - check the documentation. So, in your code, the "mouse" variable might be null. You can't call methods on a null reference without getting a NullPointerException! Another possible fix:
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if (mouse != null) {
            mouseXcalc = mouse.getX();
            mouseYcalc = mouse.getY();
        }
darkmist255 darkmist255

2011/11/24

#
Thanks! And I would say that doing "if (someVariable != null)" could help with many methods that can return null?
You need to login to post a reply.