I had an idea for a project i could do, writing a 2d game framework.
I want to do collision detection and have a collision listener CollisionListener.
I only have a vague idea of how listeners work, and I have no experiance writing one, I've just used them.
Can someone explain the internal workings of listeners or give me a link to a page that does?
-Jonathan
12-09-2004, 06:14 PM
sjalle
Listeners are objects that sign on to another objects listener-list.
That object checks its listeners-list when events occur and informs the listenersof the event using a defined interface. Here is a simple example, note: this must be coded in three separate java-files...
Code:
/**
* the interface used by the listener
*/
public interface BroadcastUser {
public void changeWasMade (Object change);
}
/**
* The class implementing the listener interface
*/
public class AnyClass implements BroadcastUser {
protected Broadcaster bc=new Broadcaster();
public AnyClass () {
bc.addBroadCastUser(this);
}
public void changeWasMade (Object change) {
System.out.println("Change reported:"+change.toString());
}
}
/**
* The class that reports to the listeners
*/
public class Broadcaster {
ArrayList broadCastListeners=new ArrayList();
public Broadcaster() {}
// this class only recognizes its listeners as BroadcastUsers
public void addBroadCastUser(BroadcastUser bu) {
this.broadCastListeners.add(bu);
}
// in this method the change (or whatevver) is reported
// to all the registered listeners
public void aChangeMethod(Object aChange) {
for (int i=0; i<boadCastListeners; i++) {
BroadcastUser bu=(BroadcastUser)broadCastListeners.get(i);
bu.changeWasMade(aChange);
}
}
}
12-13-2004, 12:49 PM
Pie-rate
Thank you.
I still have to write the collision detection and I was wondering if anyone has any suggestions about that.
12-13-2004, 01:56 PM
sjalle
Hint: you have to have a way of telling that two objects occupy the same area on the driveway at the same time, so you must have a driveway/area, and the location of each driver in that area at any time.