I am attempting to change the background color of the GameWorld based on a menu selection made using a button called StartButton that is placed in the Start World. Essentially I am using the StartWorld world to construct a start menu using actors as buttons.
Here is the code used in the StartButton
and this is the GameWorld code
Lastly here is the StartWorld code
Can anyone help me create the mechanism to set the index value in the StartButton class and use it in the GameWorld
public class StartButton extends Actor
{
public StartButton()
{
GreenfootImage img = new GreenfootImage(300,100);//Create Greenfoot image
img.setColor(Color.BLACK);//Add Background Color
img.fillRect(0,0,300,100);//Fill Background
img.setColor(Color.WHITE);//Add Text Color
Font font = new Font("arial",true,false,30);//Define font
img.setFont(font);//Set defined font
img.drawString("Click here to start",25,60);//Add Text
setImage(img);//Create image
}
/**
* Act - do whatever the StartButton wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
if (Greenfoot.mouseClicked(this))//Allow user to click object
{
//This is where the code to change index value should be
Greenfoot.setWorld(new GameWorld());//switch to GameWorld
}
}
}public class GameWorld extends World
{
int index = 0;
/**
* Constructor for objects of class GameWorld.
*
*/
public GameWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1);
if(index == 0)
{
GreenfootImage background = getBackground();//Create Image
background.setColor(Color.BLUE);//Add Background color
background.fillRect(0,0,getWidth(),getHeight());//Fill image with color
}
if(index == 1)
{
GreenfootImage background = getBackground();//Create Image
background.setColor(Color.RED);//Add Background color
background.fillRect(0,0,getWidth(),getHeight());//Fill image with color
}
}
}public class StartWorld extends World
{
/**
* Constructor for objects of class StartWorld.
*
*/
public StartWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1);
prepare();
}
/**
* Prepare the world for the start of the program.
* That is: create the initial objects and add them to the world.
*/
private void prepare()
{
StartButton startButton = new StartButton();
addObject(startButton,294,298);
}
}
