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

2015/11/19

Why does one of these work, but the other doesn't?

mickyg mickyg

2015/11/19

#
This works.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class StartButton here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class StartButton extends Actor
{
    
    /**
     * 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() 
    {
        Backdrop backdrop = (Backdrop)getWorld();
        backdrop.prepare(); 
    }
}
This doesn't. Why?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class StartButton here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class StartButton extends Actor
{
    
Backdrop backdrop = (Backdrop)getWorld();


    /**
     * 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() 
    {
              backdrop.prepare(); 
    }
}
danpost danpost

2015/11/20

#
The 'act' method is called after the actor is added into the world; but, the field is assigned its initial value when the actor is being created (before being added into the world). In you second code-set, 'getWorld' returns null, meaning the actor is not in any world at the time the assignment is made. This assignment at line 12 is only executed once.
mickyg mickyg

2015/11/20

#
Thank you!
You need to login to post a reply.