[Logo]
Forums Register Login
trouble with mouseEvents
Hello everyone,
I'm pretty new to java so I would very much appreciate any and all help.

I'm working on a program to play a game where the user needs to be able to move an object on the screen by moving the mouse. I've spent a while trying to figure out why my code is not working... it throws a null pointer exception error. I've posted my code below (leaving out lots of constants)... thanks very much in advance!



[UD: added linebreak to preserve layout ]
[ October 17, 2008: Message edited by: Ulf Dittmer ]
Can you post the full error stack?

Cheers,

Iv�n
 
Originally posted by mary confused:
//public GRect paddle;

// here is where i'm having trouble - if i don't initialize
//"paddle" in the line above, it says paddle cannot be resolved,
// even though i add paddle in drawPaddle(). and if i do initialize
// it, then it says paddle returns null. ?

public void mouseMoved(MouseEvent e) {
paddle.setLocation(e.getX(), HEIGHT-PADDLE_Y_OFFSET);
}


Hi,

Welcome to JavaRanch!

The problem is that you don't initialize "paddle", even if you include that line; all you do is declare it. Declaring a variable makes the name meaningful, but it doesn't create an object. You want a GRect for the "paddle" variable to refer to, so somewhere, at some point, you need

paddle = new GRect(...);

and this has to happen before you can call paddle.setLocation(), or you'll get that NullPointerException (which is telling you, in Java-ese, that paddle isn't refering to any object.)
thank you so much! the clarification between declaring and initializing helped a lot. cheers!
Everybody does that sort of thing, so think nothing of it.
And welcome to JavaRanch, Mary Caldwell
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Dec 11, 2017 12:11:50.