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

2014/1/21

Button

pr2alede pr2alede

2014/1/21

#
I have a button which starts a game. When the mouse hovers over the button, I want it to change the image. The code works here but then changes back to image1 straight away. Is there a way i can make the image stay if the house is hovering over it.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Start here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Start extends Actor
{
    
    private GreenfootImage image1 = new GreenfootImage("dechrau.png");
    private GreenfootImage image2 = new GreenfootImage ("dechrau2.png");
    private int counterx = 0;
    /**
     * Act - do whatever the Start wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
          if(Greenfoot.mouseMoved(this)){
          setImage(image2);
        }
          else
          {setImage(image1);
    }  
      if(Greenfoot.mouseClicked(this))
           Greenfoot.setWorld(new CrabWorld());       
    } 
}  




danpost danpost

2014/1/21

#
What is happening is that 'mouseMoved(this) will be false if the mouse does not move at all. So, if it is still on your button, you will not get the alternate image. What you need to do is keep track of whether it is on the button or not.
// add instance field
private boolean mouseHovering;
// in act method
if (!mouseHovering && Greenfoot.mouseMoved(this))
{
    setImage(imae2);
    mouseHovering = true;
}
if (mouseHovering && Greenfoot.mouseMoved(null) && !Greenfoot.mouseMoved(this))
{
    setImage(image1);
    mouseHovering = false;
}
Anyways, with the boolean, you are not setting the image of the actor every single act cycle (only at the time the mouse moves from off to on and back).
pr2alede pr2alede

2014/1/21

#
Great that's worked. Thankyou
You need to login to post a reply.