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

2017/2/8

Greenfoot.getMouseInfo() returns null problem

perhapss44 perhapss44

2017/2/8

#
Hello everyone. I am trying to create a very basic button and i use Greenfoot.getMouseInfo() function to... be able to compare if the cursor is "above" the button. The problem is.. it was always returning null..and i don t know how to change that. Here is the code:
MouseInfo mouse = Greenfoot.getMouseInfo();
    
    public void act() 
    {
        MENU(world);
        if (mouse != null){
            mouseinput(mouse, wStart);
        }
    }

    public void mouseinput(MouseInfo m, World w){
        if (mousePressed(m, world.getWidth()/2 - 128, 100, 200, 100)){
            bg.running = true;
        }
    }
    public boolean mousePressed(MouseInfo m, int x, int y, int width, int height){
        if (Greenfoot.mouseClicked(world)){
            if(m.getX()>x && m.getX()<x+width){
                if (m.getY()>y && m.getY()<y+height){
                    return true;
                }
            }
        }
        return false;
       
    }
I would want to use what Greenfoot offers..but if i can't find a sollution..i guess i'll use MouseListener
Super_Hippo Super_Hippo

2017/2/8

#
Try to move line 1 to where you need it and not outside methods. Greenfoot.getMouseInfo() returns the current state of the mouse. You can't just call it once and try to get something new from it at a later state.
danpost danpost

2017/2/9

#
Super_Hippo wrote...
Greenfoot.getMouseInfo() returns the current state of the mouse.
To elaborate, if no mouse action is detected (basically any movement or clicks), no MouseInfo object will be returned and the value of the reference will be 'null'. Otherwise the last action would continue to be returned, where it may no longer be the current state of the mouse. I usually use a combination of 'mouseMoved' calls to determine hover state; however, using a field to keep track of the current state is useful to determine the exact moment the state changes.
// field
private boolean mouseOver = false;

/**  in act  */
// gaining hover
if (!mouseOver && Greenfoot.mouseMoved(this))
{
    mouseOver = true;
    // whatever you do when button gains mouse hover
}
// losing hover
if (mouseOver && Greenfoot.mouseMoved(null) && !Greenfoot.mouseMoved(this))
{
    mouseOver = false;
    // whatever you do when button loses mouse hover
}
You need to login to post a reply.