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

2019/3/4

NullPointerException when trying to get mouseX/Y

Zestix Zestix

2019/3/4

#
Hey, what I wanted to do was to get the mouse coordinates. Doing that though gives me a nullpointerexception and I dont really understand why. This is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if (diffT == 0)
        {
            if (mouse.getX()>89 && mouse.getX()<364 &&
            mouse.getY()>545 && mouse.getY()<677)
            {
                diff = 1;
                diffT++;
            }
            if (mouse.getX()>786 && mouse.getX()<1155 &&
            mouse.getY()>545 && mouse.getY()<677)
            {
                diff = 2;
                diffT++;
            }
            if (mouse.getX()>1236 && mouse.getX()<1500 &&
            mouse.getY()>545 && mouse.getY()<677)
            {
                diff = 3;
                diffT++;
            }
        }
Super_Hippo Super_Hippo

2019/3/4

#
Add the following around your code, don't get the MouseInfo object when creating the object.
1
2
3
4
5
MouseInfo mouse = Greenfoot.getMouseInfo();
if (mouse != null)
{
    //your code
}
danpost danpost

2019/3/4

#
Actually, I doubt this code should be executed unless the mouse was first found to have either moved or been clicked. Also, using diffT just puts off till later what you can do now. I am sure you have code somewhere that says:
1
2
3
4
if (diffT > 0)
{
    // do something
}
You can do that something within the code given (immediately) instead of asking whether it should be done in some code executed later.
Zestix Zestix

2019/3/4

#
I fixed it, it just seemed like the coordinates caused the error( I don't know why) and I should have given more background information to help you understand what I wanted to do.
danpost danpost

2019/3/4

#
Zestix wrote...
I fixed it, it just seemed like the coordinates caused the error( I don't know why) and I should have given more background information to help you understand what I wanted to do.
I was not the coordinates. It was the mouse reference. If no mouse action occurs between one act and the next, no MouseInfo object is created and getMouseInfo will return a null value (which you cannot get coordinates from).
Zestix Zestix

2019/3/4

#
danpost wrote...
Zestix wrote...
I fixed it, it just seemed like the coordinates caused the error( I don't know why) and I should have given more background information to help you understand what I wanted to do.
I was not the coordinates. It was the mouse reference. If no mouse action occurs between one act and the next, no MouseInfo object is created and getMouseInfo will return a null value (which you cannot get coordinates from).
Ah thanks for explaining that to me
You need to login to post a reply.