Question

I am teaching a class in Greenfoot, and I am stuck over something that seems trivial.

I need the option, that whenever someone drags an actor in my world, then drops it a method is triggered. How is this done?

Was it helpful?

Solution

Simply override the addedToWorld() method on your actor. The following example for instance defines an actor that always positions itself at a position of 50,50 when inserted into the world:

public class MyActor extends Actor {

    @Override
    public void addedToWorld(World world) {
        setLocation(50,50);
    }

}

The setLocation() call is of course arbitrary, whatever code you provide in that method will be executed as soon as the actor has been added to the world (whether interactively via drag / drop, or programmatically.)

As a side note, you can also put some initialisation code in the actor's constructor, but since this happens before the actor has been placed into the world, any code setting the actor's location, rotation, etc. will throw an exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top