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

2015/3/25

Rollover button help

Cytotoxin Cytotoxin

2015/3/25

#
Hello, I'm wondering if you guys can help me. I've created a button that is supposed to hover when the mouse is moved over it. I have successfully done that but the rollover image flashes before returning to the non hover image This is the code:
public class Start extends Actor
{
    public void act() 
    {
        hover();
    }    
    
    public void hover()
    {
         if (Greenfoot.mouseMoved(this))
         {
         setImage("Start rollover.png");
        }
        else
        {
            { setImage("Start.png"); }
        }
    }
}
danpost danpost

2015/3/25

#
The problem is that if the mouse stops moving while over the button, the 'mouseMoved' will return a false value and therefore your non-rollover image will appear. Therefore the conditions that are required for the image to change are: (1) a mouse move event must occur (anywhere) (2) the previous hover state is not the current hover state Now, in order to know the previous hover state, a boolean field is required to store it so it can be compared to the current state.
public class Start extends Actor
{
    private boolean mouseHover;

    public void act()
    {
        hover();
    }

    private void hover()
    {
        if
        (
            Greenfoot.mouseMoved(null) && // mouse moves
            mouseHover != Greenfoot.mouseMoved(this) // state changes
        )
        {
            mouseHover = ! mouseHover; // save new state
            if (mouseHover) // change image
                setImage("Start rollover.png");
            else
                setImage("Start.png");
        }
    }
}
Cytotoxin Cytotoxin

2015/3/26

#
Thank you very much danpost, you have helped me greatly.
You need to login to post a reply.