Skip to content

Creating an EntityListener

Elliot Ford edited this page May 25, 2015 · 12 revisions

What is an EntityListener?

An EntityListener is a listener that is fired upon creation, transfer or death of an Entity within in an EntityContainer (see Creating, getting and killing entities and Transferring an Entity). When a listener method is fired an EntityEvent is created and supplied for the trigger.

What is an EntityEvent?

An EntityEvent contains all the information about the specific trigger event. An event contains the Entity and the container that this event was fired from (which could be an Entity).

Creating a listener

EntityListener is an interface with each method signifying a different trigger situation.

void entityCreated(final EntityEvent event)

void entityKilled(final EntityEvent event)

void entityReceived(final EntityEvent event)

void entityTransferred(final EntityEvent event)

To avoid having to supply empty dummy implementations of each method EntityListener methods are all default. The below listener outputs the entity ID of every newly created entity:

EntityListener listener = new EntityListener() {

    @Override
    public void entityCreated(final EntityEvent event) {
        System.out.println(event.getEntity().getID());
    }
}

Adding a listener

This will associate the listener to the EntityContainer

EntityListener listener = /* See above */

EntityContainer container = new DefaultEntityContainer();
container.addEntityListener(listener);

Removing a listener

This is disassociate the listener from the container.

EntityListener listener = /* See above */

EntityContainer container = /* Previously created container */
container.removeEntityListener(listener);

Using multiple listeners

EntityContainer offers similar management of EntityListeners as is does to entities.

All listeners: container.getEntityListeners()

Remove listeners: container.removeEntityListeners()

Clone this wiki locally