Hey there,
so basically I decided to make a Button (CTA Buttons) class. It basically allows you to create a button in the world and changes the Image once you hover over the button and does something once you click the button. Works fine with one button but as soon as I add another one to the world it can only keep track of one button. I know where the problem is but I dont know how to fix that. Take a look at the code first.
The problem is that I can only keep track of the first Button since im calling 0 as index to set the Image and "this" for the Mouse events.
Please fix.
//My World
public MainScreen()
{
Button btn = new Button("startGame.png");
addObject(btn,500,300);
Button btn2 = new Button("startGame.png");
addObject(btn2,300,200);
}//Button Class
public class Button extends Actor
{
public String imgName, extension;
private Button btn;
public Button(String image)
{
imgName = image;
extension = imgName.substring(imgName.lastIndexOf('.'));
CreateButton(imgName);
}
public void act()
{
if(Greenfoot.mouseClicked(this))
{
switch(imgName.substring(0,imgName.lastIndexOf('.'))) //Remove File Extension
{
default:
break;
case "startGame":
//SwitchWorld();
}
}
/*Button Hover Effect*/
if(Greenfoot.mouseMoved(null) && Greenfoot.mouseMoved(this))
getWorld().getObjects(Button.class).get(0).setImage(imgName.substring(0,imgName.lastIndexOf('.')) + "1"+extension);
else if(Greenfoot.mouseMoved(null) && Greenfoot.mouseMoved(this) == false)
getWorld().getObjects(Button.class).get(0).setImage(imgName);
/*Button Hover Effect*/
}
private void CreateButton(String image)
{
GreenfootImage button = new GreenfootImage(image);
setImage(button);
}
}

