Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

"fixing" event listener order...

800382Oct 13 2004 — edited Oct 14 2004
I've read some places that event listeners are called in the order they are added. But I've also read that they may not be. Anyone know for sure? At least with regards to the standard AWT/Swing classes?

If they do run in order added.... Then can someone smack me upside the head and point out the "issues" there might be with using a method like this here that I wrote to install a listener "first" in the list? Of course, instead of using reflection, I could implement it with specific components, but this would work (more or less) for any Component, instead of writing dozens of listener-type- and component-type-specific versions.
public static boolean addEventListener(Component comp, EventListener listener) {
	try {
		Class listenerClass = listener.getClass();
		String listenerName = listenerClass.getName().substring(listenerClass.getName().lastIndexOf("."));
		EventListener[] listeners = (EventListener[])comp.getListeners(listenerClass);
		Method addMethod = comp.getClass().getMethod("add"+listenerName, new Class[]{ listenerClass });
		Method removeMethod = comp.getClass().getMethod("remove"+listenerName, new Class[]{ listenerClass });
		for(int i = 0; i < listeners.length; i++) {
			removeMethod.invoke(comp, new Object[]{ listeners[i] });
		}
		addMethod.invoke(comp, new Object[]{ listener });
		for(int i = 0; i < listeners.length; i++) {
			addMethod.invoke(comp, new Object[]{ listeners[i] });
		}
		return true;
	} catch(Exception e) {}
	return false;
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 11 2004
Added on Oct 13 2004
8 comments
372 views