In Java, every time I want to create a new custom event, I usually do this by adding 3 methods, namely:
addDogEventListener(EventListener listener); removeDogEventListener(EventListener listener); dispatchDogEventListener(DogEvent event);
Then, if I want to send another event, say CatEvent, I will have to create all these 3 methods again:
addCatEventListener(EventListener listener); removeCatEventListener(EventListener listener); dispatchCatEventListener(CatEvent event);
Then, if I want to control only one kind of CatEvent event, say Meow, do I need to copy all these 3 methods again and again ?! How do addCatMeowEventListener (); ... etc?
And, as a rule, I need to send more than one kind of event. It will be very untidy for the whole class to be populated with many methods for passing and handling events. In addition, these functions have very similar code, for example, looping through EventListenerList, adding events to the list, etc.
Is this how I should do event dispatching in Java?
Is there any way I can do this:
mainApp.addEventListener(CatEvent.MEOW, new EventHandler() { meowHandler(Event e) { }); mainApp.addEventListener(CatEvent.EAT, new EventHandler() { eatHandler(Event e) { }); myCat.addEventListener(DogEvent.BARK, new EventHandler() { barkHandler(Event e) { myCat.run() });
That way, I can just handle different CatEvent types in different classes and eventHandler functions, and I donβt need to continue to create different methods of listening for events for different events?
Maybe something is missing for me in handling Java events, but is there a tidier way that I do not need to save and paste into 3 methods, and also create so many different event objects for all the different methods that I want to send?
Thanks!