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

2013/6/16

Nullpointer exception?

allekalle allekalle

2013/6/16

#
Hi! I made the below code in an actor class. First the code worked as expected, the object was possible to drag on the left side of the world. Then I started getting nullpointer exceptions and the code didn't do anything any more. Why do I get the exception? Thanks! Karl import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class ButtonDestroyer extends Actor { public void act() { MouseInfo mouse = Greenfoot.getMouseInfo(); if (mouse.getX()< 600) { mouseDragging(); } } private void mouseDragging() { if (Greenfoot.mouseDragged(this)) { MouseInfo mouse = Greenfoot.getMouseInfo(); setLocation(mouse.getX(), mouse.getY()); } } }
danpost danpost

2013/6/16

#
'getMouseInfo' sometimes returns 'null' and therefore you cannot use 'getX' on it without first making sure that it is not 'null'. Change 'if (mouse.getX()<600)' to 'if(mouse != null && mouse.getX()<600)'.
allekalle allekalle

2013/6/16

#
Thanks! That fixed it.
You need to login to post a reply.