-1

I am making a game where you shoot down birds. I've made an actor that acts as a Crosshair, following the mouse around.

This is the code which is generating the error (setLocation is line 18):

MouseInfo mouse = Greenfoot.getMouseInfo();
setLocation(mouse.getX(), mouse.getY());

And the error code:

java.lang.NullPointerException
    at Crosshair.act(Crosshair.java:18)
    at greenfoot.core.Simulation.actActor(Simulation.java:565)
    at greenfoot.core.Simulation.runOneLoop(Simulation.java:523)
    at greenfoot.core.Simulation.runContent(Simulation.java:213)
    at greenfoot.core.Simulation.run(Simulation.java:203)
Patrick Reck
  • 11,246
  • 11
  • 53
  • 86

1 Answers1

1

If you're having a null pointer exception in the code you wrote then that means that your mouseinfo object is null.

According to the documentation:

getMouseInfo

public static MouseInfo getMouseInfo() Return a mouse info object with information about the state of the mouse.

Returns: The info about the current state of the mouse, or null if the mouse cursor is outside the world boundary (unless being dragged).

Basically this means your mouse if out of boundaries when that method is called.

In order to help you out more please describe what exactly where you hoping to achieve.

Community
  • 1
  • 1
norbitheeviljester
  • 952
  • 1
  • 6
  • 17
  • The code here is making the Crosshair actor follow the mouse around. And since it's doing what it's supposed to do, i don't understand this error – Patrick Reck Sep 06 '12 at 06:17
  • So the error probably happens when your mouse leaves the application screen? Meaning the actor can't go there with you. You should have a null guard after the getmouseinfo method – norbitheeviljester Sep 06 '12 at 06:20
  • if (mouse != null) { setLocation(mouse.getX(), mouse.getY()); } worked out :-) – Patrick Reck Sep 06 '12 at 06:27