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

2017/3/9

Changing BackgroundImage in MyWorld

wueschn wueschn

2017/3/9

#
I have a little problem, but I don`t manage it to solve. I want to change the Background Image of MyWorld by clicking the Playing Area. It works for one time, but I am not able to change the Image by every click. Also no error is shown ... Thanks a lot for helping
public class MyWorld extends World
{

    private GreenfootImage image2 = new GreenfootImage("board.jpg");
    private GreenfootImage image1 = new GreenfootImage("brick.jpg");
    public MyWorld()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
        this.setBackground(image2); 

    }

    public void act()
    {
        this.myClicking();
    }

    public void myClicking()
    {
        if(Greenfoot.mouseClicked(this))
        {

            if(this.getBackground().equals(image1))
            {
                this.setBackground(image2);
                

            }
            else
            {
                this.setBackground(image1);
            }
        }
    }

}
danpost danpost

2017/3/9

#
You must realize that the image returned by 'getBackground', which is the size of your world, cannot be equal to the image from the files, which are much smaller and tiled onto the background to create the background image. Best bet is to assign the image fields to the image returned with 'getBackground' after setting the background:
// for lines 24 through 35
if (this.getBackground() != image1)
{
    this.setBackground(image1);
    image1 = this.getBackground();
}
else
{
    this.setBackground(image2);
    image2 = this.getBackground();
}
Because lines 5 and 10 actually get a reference to the actual background image, we can use standard comparison operators instead of 'equals'. I used '!=' here out of preference -- checking for equality can sometimes run into some issues (although it probably will not here).
wueschn wueschn

2017/3/9

#
@danpost Your solution works perfect, thanks a lot!! I tried now to combine your solution with my coding and because of your explanation it also works! It is sentence 5 and 10 that matters.
public void myClicking()
    {
        if(Greenfoot.mouseClicked(this))
        {


            if(this.getBackground().equals(image2))
            {
                this.setBackground(image1);
                image1 = this.getBackground();
            }
            else
            {
                this.setBackground(image2);
                image2 = this.getBackground();
            }
        }
    }
You need to login to post a reply.