Event Dispacher in Java - java

I need to to make for school a simple "strategy game simulator". To do this I need to make an Event Dispatcher (event loop) that will send the event to the registered parties. For example, I have resources on the map. One event is "resource at location 1 depleted". And one "player" is interested on that event.
How would I create the dispatcher (and register one player for one particular event). Also, how does the dispatcher check for the event? Does it simply do something like if(resourceLocation1.getNoResource()==0) trigerEvent(); or is there some other, more elegant way.
I worked with event listeners (mostly in ActionScrip3) but never made a custom event and a custom event dispatcher. Any help is appreciated, including some links to some tutorials or sample codes.
If I am not clear what I am searching for please let me know and I will try to explain it better
Thanks.

Your EventDispatcher does not need to check every possible condition and notify all possible listeners. Just notify listeners registered for a certain type of event.
Register Player to be notified depending on the game event
eventDispatcher.register(player, Events.RESOURCE_DEPLETION_EVENT);
Then your Resource would supply an event when resources reached 0
class Resource {
public void deplete(int amount) {
this.amount -= amount;
if (this.amount <= 0)
eventDispatcher.notify(this, Events.RESOURCE_DEPLETION_EVENT);
}
}
Otherwise you are going to end up with a massive logic-containing event loop that eats up performance and will be difficult to debug.

Java has a built-in thread-safe Observer pattern you can use.
To write your own you would have Player implement a ResourceDepeletionListener interface and add it to an array of listeners in your Resource class. When the resources reach zero they call resourcesDepleted() on all ResourceDepeletionListener objects.

What about implementing an observer pattern?
For instance, you can have a ResourceObserver, which registers a particular Resource as an observable. From there, you can have Player objects register as observers to your ResourceObserver. A map object will hold all the resources. In your event loop, you will have something like:
...
Map.updateResources();
...
So for instance, when you call updateResources, all the map resources will check if they have been depleted. If a resource has been depeleted, it will notify it's ResourceObserver, which will in turn notify all registered players for that resource.

Related

Java Swing Listeners [duplicate]

I looked for this online, but couldn't find an adequate explanation to what it exactly does. What I saw was a Java Interface and it was passed as a parameter in another class as a "Listener". People added various listeners to a list and called them all through a single method.
I'm not sure why I would use it. Can someone care to explain?
This is my original help post where someone told me to use listeners.
Link
In the code example that you linked the KillMonsterEventListener
public interface KillMonsterEventListener {
void onKillMonster ();
}
provides a way for users of your API to tell you something like this:
Here is a piece of code. When a monster is killed, call it back. I will decide what to do.
This is a way for me to plug in my code at a specific point in your execution stream (specifically, at the point when a monster is killed). I can do something like this:
yourClass.addKillMonsterEventListener(
new KillMonsterEventListener() {
public onKillMonster() {
System.out.println("A good monster is a dead monster!");
}
}
);
Somewhere else I could add another listener:
yourClass.addKillMonsterEventListener(
new KillMonsterEventListener() {
public onKillMonster() {
monsterCount--;
}
}
);
When your code goes through the list of listeners on killing a monster, i.e.
for (KillMonsterEventListener listener : listeners) {
listener.onKillMonster()
}
both my code snippets (i.e. the monsterCount-- and the printout) get executed. The nice thing about it is that your code is completely decoupled from mine: it has no idea what I am printing, what variable I am decrementing, and so on.
Listener is a common form of implementing the observer design patter in Java. This technique is also referred to as the callback, which is a term coming from the world of procedural languages.
Observers register themselves by the observable, which in turn calls back the observers whenever some event occurs or when they should be notified about something.
Many framework libraries play the role of the observable, e.g.:
You register yourself (i.e., your implementation of the listener interface) as a listener of incoming messages in a messaging middleware.
You register yourself as a listener of some changes made by the user in the operating system.
You register yourself as a listener of GUI events, such as a button was click on.
Example in Java code:
Part 1 - The observable entity
import java.util.LinkedList;
import java.util.List;
public class Observable {
private List<Observer> observers;
public Observable() {
observers = new LinkedList<>();
}
public void addObsever(Observer observer) {
observers.add(observer);
}
private void notifyObservers(String whatHappened) {
for (Observer observer : observers) {
observer.onSomethingHappened(whatHappened);
}
}
public void doSomeStuff() {
// ...
// Do some business logic here.
// ...
// Now we want to notify all the listeners about something.
notifyObservers("We found it!");
// ...
// Do some business logic here
// ...
}
}
Part 2 - The observer/listener interface
public interface Observer {
void onSomethingHappened(String whatHappened);
}
Part 3 - Basic implementation of the observer/listener interface
public class MyObserver implements Observer {
#Override
public void onSomethingHappened(String whatHappened) {
System.out.println(whatHappened);
}
}
Part 4 - Putting it all together
public class Main {
public static void main(String[] args) {
// Create the observable.
Observable myObservable = new Observable();
// Create the observers (aka listeners).
Observer myObserverA = new MyObserver();
Observer myObserverB = new MyObserver();
// Register the observers (aka listeners).
myObservable.addObsever(myObserverA);
myObservable.addObsever(myObserverB);
myObservable.doSomeStuff();
}
}
And the result on standard output will be:
We found it!
We found it!
This is part of a programming paradigm called event-driven programming. Objects send messages to other objects on certain occasions, for example when they change. This is used often in GUI programming. Each GUI widget is implemented by a class. When you want to handle e.g. mouse clicks from the user, you add a listener (also called event handler) to GUI widget. When the user clicks on the widget, the widget sends the event to the registered listener(s) so that the application can respond to the mouse click. This seperates the framework (the GUI widget class) and the application code. (In some GUI frameworks, such as Swing, you can add an arbitrary number of listeners to an object; in others, you can specify only one.)
Also in other areas event-driven programming is useful. You might want to observe an object (see Observer pattern). For example, a collection which supports this, might send an event if its contents change. If you need to perform some processing if this occurs, you can add yourself as a listener to this class. The alternative would be to call the post-processing every time you add an item to the collection, but this error-prone.
Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener.
Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.
You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur.
Here is the blog post for Servlet Listener
http://array151.blogspot.in/2016/12/servlet-listener.html
Use a listener to let other code inform you of "conditions"/"events". For instance a "mouse listener" could be called if the mouse would have been moved/clicked/dragged. It depends on your application why it provides for listeners.
Listeners do some work when an event occurs. They are called as "Event Listeners".
Events like click, hover etc..
For Example, we have ActionListener interface in Java. It calls actionPerformed() method when an event occurs.
You can refer http://java.about.com/od/a/g/Actionlistener.htm for more info.
Listeners are used for notify about state changes. You can think about Listeners in most of time as Observers, so every time something interesting happen your listener will be called.
You can read more about patterns in Java on following websites:
http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial
http://www.developer.com/java/implementing-behavioral-patterns-in-java.html

Vaadin7: Tracking whether a user is active (DOM Event Handler)

We are currently porting our app to vaadin 7 and I want to track wether a user has been active during the last 30s or so.
We used to track user activity in a custom CommunicationManager, but since this class is deprecated, I figured we might have to try differently.
I created an extension that I extend the UI with.
For simplicity's sake let's say, we count clicking and keyboard usage as user activity:
// this is the extend method in the extension connector
#Override
protected void extend (ServerConnector target) {
UIConnector uiConnector = (UIConnector) target;
VUI uiWidget = uiConnector.getWidget();
uiWidget.addDomHandler(this.keyPressed(), KeyPressEvent.getType());
uiWidget.addDomHandler(this.mouseClicked(), ClickEvent.getType());
}
The extension will then schedule a timer that will call the server via RPC every 30s, but only if the user has been active.
This Timer works. What does not work is the DOM Events, they never seem to reach the Event Listeners I added.
What am I doing wrong?
Based on your implementation, I would suggest you give Refresher add-on a try. It works in similar manner but gives you more control regarding polling interval, server-side listener. Plus, you don't have to maintain it.
The other alternative would be taking advantage of Vaadin polling support (see https://vaadin.com/wiki/-/wiki/Main/Using%20polling).

Are there any standard techniques and/or examples of collapsing multiple events in Java?

Let me first sketch the concrete situation I find myself in, although my question is actually more general. I'm writing a component containing several sliders and I have listeners listening for events from these sliders. When one of these sliders changes I want my component to send an event to its own listeners to notify them that its state has changed. I would however like to limit the number of events that are sent, i.e. if there are several events waiting when my component notifies its listeners, I would like to collapse all these events into a single event.
My question is whether there are standard techniques for this. If so, any example would be welcome, because I couldn't find any. (Maybe collapsing is not the correct terminology?)
I believe collapsing is the correct term. An example class from the Java Core libraries that implements such behavior is RepaintManager. I would check out it's source code to see how it collapses multiple repaint requests.
Before you do any such thing you should make sure that it is really necessary.
I guess you would need to access the EventQueue from your listener. When an event triggers the callback method, this method should first look in the queue to see if there are more recent events of the relevant type and, if so, process the most recent event only and then remove all events of that type from the queue.
Since the callbacks are always on the Swing (awt) event thread, you don't need to worry about concurrency.

What's the difference between Event Listeners & Handlers in Java?

In general terms of java, there are listeners & handlers for events.
I mean I use them unknowingly, just whichever is available in the API.
My question is, in what case do we use listeners and in what case do we use handlers for events?
What's the difference between them? Characteristics??
I've searched for reasons and I couldn't find a proper explanation for Java.
There's no formally defined difference between listeners and handlers. Some people would probably argue that they are interchangeable. To me however, they have slightly different meaning.
A listener is an object that subscribes for events from a source. Cf. the observer pattern. Usually you can have many listeners subscribing for each type of event, and they are added through addXyzListener methods.
Example: The MouseListener in the Java API.
A handler is an object that is responsible for handling certain events. A typical scenario would be to provide a handler for a specific event/task as an argument to a constructor, or set the handler through a setXyzHandler method. In other words, you usually have one handler for each type of event.
Example: The MemoryHandler in the Java API.
The most basic difference is the association
Listener is associated with Event Source (Ex: key board)
Handler is associated with an Event (Ex: keydown)
Generally speaking, there will only one central Handler Manager which manages all the events, while in case of Listener each Entity which wants to listen, will have to manage their own Collection of listeners
This is the way I see it:
A listener watches for an event to be fired. For example, a KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue and so on.
The handler is responsible for dealing with the event. Normally, listeners and handlers go hand-in-hand. For example, the KeyListener tells the ExitHandler that "the letter Q was pressed" and the handler performs logic such as cleaning up resources and exiting the application gracefully. Similary a ButtonClickListener would tell the same ExitHandler that the "Exit button was clicked". So, in this case you have two different events, two different listeners but a single handler.
A listener is an object that is notified when an event occurs, and it has 2 major requirements-
1-it must have been registered with one or more sources to receive notifications about specific types of event
2-it must implements methods to receive and process these notifications.
Handler is responsible for dealing with events.
To my mind, the most important difference is fact that we use listeners per event's source, in contrary to handler, which is per event type.
A listener, listens for events which are data value objects which describe an event. When the event occurred and the order of events is often important. Pressing key '0' followed by '1' is different to '1' and '0'.
A handler, handles a complex object e.g. a new Socket connection. The handler might process the object for any length of time. The time of object creation and order is not so important. A connection from client0 or client1 can happen in any order.
I think the difference is subtle because a concrete Listener is an event-handler too or at least has a method that can be considered an event-handler.
That is, a concrete Listener handles or manages the reaction to the event after receiving an event object(from the event-source) with all the usefull informations about the event just occurred(on the event-source).
As this Listener has to implement an xxxListener interface that forces him to implement at least one method that is in turn executed by the event-source object when the event occurs, so the Listener itself can be considered an handler and more precisely, the method of the Listener interface implemented by the Listener object can be considered the real event-handler.
So i view the event-handler as just the code that is executed in reaction to an event.
This is different from a Listener object that is an element of a more abstract concept such as an Observer design pattern.
This is my personal view of the subject.
They're conceptually the same thing - an object that performs some action in response to a UI event. Generally, in Swing, these objects are called "handlers" at the look-and-feel level (for handling low-level widget events), and "listeners" at the more abstract UI level (where you'll be implementing your application logic).
EventHandler is introduced in the JavaFX for all the UI controls. Whereas the Listener is borrowed for Observables, such as properties.
The EventHandler is a way to distinguish observable events and the ui events.
I've been trying to make sense of all the info and I'm lost. I've looked at Delphi (Pascal), C, C++, java... nothing is clear.So, after a month, this is the problem as I see it. I may be totally off track, so please tell me... politely, please.
One event sender, one catcher as long as Sender registers the catcher. I have 4 dialog boxes that need to be updated each time a file (whose handling code is in another module than the 4 dialog boxes) changes. I considered updating each the old-fashioned way, but then I looked at Delphi events and message handling. Let's see:
File F (The Sender) is finished reading and should notify Dialogs 1..4 of the fact that there is now data for them to display and the user to play with. What is best?
Try to register Dialogs 1..4 as listeners and have the Sender trigger an OnUpdatedDataEvent somehow?
Try sending a message across the system, hoping that Dialogs 1..4 will catch it?
Notice that the event keeps things coupled while messaging do not...and are a pain to debug.
And I do wonder how the File block of code will be able to register 4 listeners (the dialog boxes)?
What I am looking at is the possibility of cascade calling, meaning caller calls one listener, whom calls the next... until it reaches the end of the chain. I even wonder if that is even possible.
An example:
Say File F is a list of languages. Now, DialogBox 1 does something to the list (adds a new language for instance); that combo box updates the F file; this in turn triggers a DataUpdatedEvent. the 4 Dialog boxes contain, say, TComboBoxes that display the language list when they pop up. I want the 4 boxes to notice the change and update their own combo box contents with the freshly updated File... without having to worry about how the combo boxes know they need to refresh their contents. If it works as envisioned the Sender parameter will carry across and the dialog box that triggered the dataUpdateEvent will be bypassed since it will already be updated. After all an if sender=self then continue to next event handler should be easy to implement.
All that because I want to exercise my brain... to prevent Alzheimer's, not very successfully I might add.
Suppose you just landed at the airport by plane at a new destination. you have someone waiting for you at the gate OR someone who will drive the taxi and take you to your hotel
The person waiting is the listener (waiting for an event like you are arriving)
The person taking you to the hotel is the event handler (the action after you've arrived)
In JS, the listener waits for an event (e.g click) the handler does something father the "click" happened
It is semantics.
Listener is interface.
Adaptor is class that implements specific interface and provides empty implementation for its methods. This helps if you do not have to implement all methods of interface.
Handler implements several interfaces or delegates calls to several interfaces.

Java: Filtering out duplicate events

I was wondering if the following is common for "regular" Java applications when receiving callback/events. Those callbacks may be triggered by user input but also by other means so it is not only related to UI events:
public void handleEvent( #NotNull final SomeEvent e ) {
final boolean process;
synchronized ( this ) {
process = !e.equals(filter);
filter = e;
}
if ( process ) {
...
}
}
Basically under some complicated scheme (very complex UI involving several views of a same model and where the user can modify the model from different screens [like in complex 3D programs]) I've got lots of events firing and I've noticed that I could filter out duplicate events using the above snippet. If an event has been processed and the next event to come is exactly identical to the last processed event (saved in the filter reference), then the event/callback is simply ignored.
It works fine. I was wondering if filtering out duplicate events was a common technique?
Not always, but usually this can be a sign that some elements of the event cascade chain aren't properly detecting that they don't need to send an event. The classic illustration is a bean setter that generates a PropertyChangeEvent even when the value hasn't changed.
While what you've done will filter these events out, it doesn't address what may be a fundamental underlying issue.
The problem is that these "errors" can combine to form infinite loops. Extending the bean example above, say you have a UI that resets its editable value based on that bean field... and resetting the UI value will also call the bean setter because proper dupe checking wasn't done there either. The first time the value is edited and endless loop will occur.
These examples are obvious when they happen but as notification hierarchies get more complicated it becomes harder to track these things down and they potentially occur at more intermittent times.
A good rule of thumb is to make every event generating component as conservative as possible. In the event (heh) you are receiving notifications from components that you can't control, and will be forwarding your own events also then a filter like the one you've setup may be the only option to prevent the spread of a potentially larger problem than just performance.
The only thing I can think of is acting on a ListSelectionEvent based on whether the selection is still changing (i.e. the user is still clicking and dragging the mouse) or whether the event represents the "final" selection event; e.g.
public class MyListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent evt) {
// Finished selecting
if (!evt.getValueIsAdjusting()) {
JOptionPane.showMessageDialog("Selection Complete!");
}
}
}
Looks like you might have a listener registered twice to the same source. That could cause it. Or possibly you've registered a single listener across multiple instances. If you're seeing strangeness, look for infinite event loops which, unfortunately, because of the way Swing program organize themselves, can happen all too easily. You'll want to break those listeners apart.
I've never done this sort of thing or encountered it. As some people point out certain controls will fire events when selections are being adjusted, but there are methods to filter those things out.
The synchronized( this ) block is suspect too since you'll always be called back on the Swing thread. If that's not true in your program then you are violating Swing's threading rule, and that could explain the problem. Bottom line is you don't need the synchronized block because Swing is single threaded.
(I'm assuming this is Swing as some other posters have, but from your code alone it's ambiguous).

Categories