Reputation: 4062
I'm currently working on a simple 2d game library for self education only.
Until know everything is working as expected.
Now I'm planning the movement and the events triggered by the 'gameflow' (e.g. timer) or the entities itselves. I was wondering if it is possible to have custom events like 'EntityEventListener' and 'EntityMotionListener'. Then I had a look at MouseListener and its parent classes. Then I wrote for each listener a listener interface and an adapter class like this:
public interface AppEntityEventListener extends EventListener
{
void onCreated(Event e);
void onDeleted(Event e);
void onStepped(Event e);
void onSelected(Event e);
}
public abstract class AppEntityEventAdapter implements AppEntityEventListener
{
@Override public void onCreated(Event e) { }
@Override public void onDeleted(Event e) { }
@Override public void onStepped(Event e) { }
@Override public void onSelected(Event e) { }
}
I've detected that I only can add the listeners to Components
and the Entity
class is not derived from a Component
respectively JComponent
.
I read a bit about Listeners but I don't get the point how to deal with it as I need them for now.
Considering that my questions are now:
Entity
class?Thanks in advance.
EDIT:
I've added all the methods like you said. So now I've got two List
objects called eventListeners
and motionListeners
each has its own add and remove function.
I have got a further question regarding the iteration, using the following code:
private void iterateListeners()
{
for (Object obj : eventListeners.toArray())
{
AppEntityEventListener l = (AppEntityEventListener) obj;
Event e = new Event(this, Event.ACTION_EVENT, this);
l.onCreated(e);
l.onDeleted(e);
l.onSelected(e);
l.onStepped(e);
}
// ... other listener ...
}
How to deal the Event at this point? Is this the right way I really have no clue ... this code above is just intuitive.
Upvotes: 1
Views: 386
Reputation: 51
See if the framework tide http://abyu.github.io/tide/ can help you. Using tide you create your own events, raise and handle those events.
Upvotes: 0
Reputation: 691655
You can add listeners to any object you like, provided the object has a method which allows adding (and removing) a listener. Just add addXxxListener()/removeXxxListener()
methods to your object.
These methods should simply add/remove the listener to/from a collection of listeners, and the object should iterate through this collection and call the onXxx()
method when appropriate.
Upvotes: 1