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

2018/7/4

Making a clickable menu

Xolkiyr Xolkiyr

2018/7/4

#
Alright, here's the underlying issue I'm having. How can I tell if an object is being hovered over or clicked on by the mouse?
danpost danpost

2018/7/4

#
Create, keep a reference to (add a field to hold the button object) and check for mouse clicks on the button in the class of the menu. Also, add a field in the class of the button to track which button is currently being hovered on. Basically, something like this:
/** THE MENU WORLD CLASS */
import greenfoot.*;

public class Menu extends World
{
    Actor buttonA, buttonB;
    
    public Menu
    {
        super(600, 400, 1);
        Button.mouseOn = null; // to clear any prior menu settings
        addObject(buttonA = new Button("Previous",  120, 350);
        addObject(buttonB = new Button("Next", 280, 350);
    }
    
    public void act()
    {
        if (Greenfoot.mouseClicked(buttonA))
        {
            // buttonA clicked codes here
        }
        if (Greenfoot.mouseClicked(buttonB))
        {
            // buttonB clicked codes here
        }
    }
}

/** THE BUTTON ACTOR CLASS */
import greenfoot.*;

public class Button extends Actor
{
    public static Actor mouseOn;
    
    public Button(String caption)
    {
        // create button image here
    }
    
    public void act()
    {
        // gaining mouse hover
        if (mouseOn == null && Greenfoot.mouseMoved(this))
        {
            mouseOn = this;
            // hover gained codes here
        }
        // losing mouse hover
        if (mouseOn == this && Greenfoot.mouseMoved(null) && !Greenfoot.mouseMoved(this))
        {
            mouseOn = null;
            // hover lost code here
        }
    }
}
You need to login to post a reply.