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

2024/10/14

Help: Why can't I just get the X position of the mouse

nubnt_ nubnt_

2024/10/14

#
I just started with greenfoot, and I'm getting the error "non-static method getX() cannot be accessed from a static context". How would I go about getting this value?
//The following code will error.
Xvel = MouseInfo.getX()*0.1;
danpost danpost

2024/10/14

#
nubnt_ wrote...
I just started with greenfoot, and I'm getting the error "non-static method getX() cannot be accessed from a static context". How would I go about getting this value? << Code Omitted >>
The getX method of the MouseInfo class is not a static method. This means you need to create a MouseInfo object first, then call the method on that object (and not on the class itself). The Greenfoot class getMouseInfo method (which IS static) will return a new MouseInfo object:
Xvel = Greenfoot.getMouseInfo().getX()*0.1;
Unfortunately, there is another problem -- you are multiplying an int value (returned by the getX method) by a double or float, which will be reduced to an integer value. There are two ways to correct this:
// casting
Xvel = ((double)Greenfoot.getMouseInfo().getX())*0.1; // casting should be to same type as Xvel is declared as

// or rearranging
Xvel = 0.1*Greenfoot.getMouseInfo().getX(); // putting the value of correct type first
You need to login to post a reply.