Java Swing Listeners [duplicate] - java

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

Related

GWT Event Bus for which benefits

I am having a hard time to understand the benefits of using the Event Bus concept in GWT .
I have gone through many examples showing how to use it. I get how it is made but i dont see why it does help .
I take example :
Button button = new Button("click");
button.addListener(new ButtonListenerAdapter(){
#Override
public void onClick(Button button, EventObject e) {
doSomething() ;// must replace it with fireEvent later :(
}
});
In order to add the event bus ability to the code above we have to introduce more code:
1)create an event class that extends Event (implement 2 methods)
2) create interface for event handler where dosomething() will be abstract
3) Implement the interface
4) The class in which the event happens has to implement HasHandler interface, intreoduce HandlerManager instance ,implement fireEvent , registers the event and fires the event.
Now my problem is that, if i have 50 UI events, i cant see the benefit of duplicating the above 4 steps where it should be. If I dont do it what is really the problem i am going to face.
Edit :
Is the fact that Events & Events handlers if they are separated in classes makes the EventBus pattern interesting?
AddContactEvent.java
AddContactEventHandler.java
RemoveContactEvent.java
RemoveContactEventHandler.java
No event bus
Example: You can buy apples from the farm directly.
Button maintains the collection of listeners. Button is aware about all listeners and needs to notify them in the loop. Button is directly coupled with the handlers.
Event bus
Example: You buy apples from a store and store buys apples from the farm. The store is a broker between you and the farm. You are not aware about the farm. The farm is not aware about you.
Event bus is broker between the event producer and event consumer. Event producer is aware about event bus but not all event consumers.
Button is not aware about the listeners. It's aware about EventBus only.
Handlers are not aware about the Button. They are aware about the bus.
Summary:
Applications without plugins may be implemented without event bus.
Applications with plugin support should be implemented with the event bus as it's not known before hand how many plugins are connected to the event producer.

What is callback in Android? [duplicate]

This question already has answers here:
Callback in Android?
(3 answers)
Closed 9 years ago.
I want to understand the concept of callback. I have searched on internet about the callbacks and there are many examples using interface, and one class is calling a method of another class using that interface. But still I can't get the main concept of callbacks, what is the purpose of using callbacks?
Here is a nice tutorial, which describes callbacks and the use-case well.
The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".
Here's a example:
class A implements ICallback {
MyObject o;
B b = new B(this, someParameter);
#Override
public void callback(MyObject o){
this.o = o;
}
}
class B {
ICallback ic;
B(ICallback ic, someParameter){
this.ic = ic;
}
new Thread(new Runnable(){
public void run(){
// some calculation
ic.callback(myObject)
}
}).start();
}
interface ICallback{
public void callback(MyObject o);
}
Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.
In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.
You create an interface first, then define a method, which would act as a callback. In this example we would have two classes, one classA and another classB
Interface:
public interface OnCustomEventListener{
public void onEvent(); //method, which can have parameters
}
the listener itself in classB (we only set the listener in classB)
private OnCustomEventListener mListener; //listener field
//setting the listener
public void setCustomEventListener(OnCustomEventListener eventListener) {
this.mListener=eventListener;
}
in classA, how we start listening for whatever classB has to tell
classB.setCustomEventListener(new OnCustomEventListener(){
public void onEvent(){
//do whatever you want to do when the event is performed.
}
});
how do we trigger an event from classB (for example on button pressed)
if(this.mListener!=null){
this.mListener.onEvent();
}
P.S. Your custom listener may have as many parameters as you want
Source
Callback can be very helpful in Java.
Using Callback you can notify another Class of an asynchronous action that has completed with success or error.
CallBack Interface are used for Fragment to Fragment communication in android.
Refer here for your understanding.
It was discussed before here.
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
I am using in the following case:
In UI I got an action from a button, for eg. the user want to download an 500mb file.
Thank I will initialize the background engine (AsyncTask class) and pass parameters to him.
On the UI I will show a blocking progress dialog and disable the user to make any other clicks. The question is: when to remove the blocking from UI? the answer is: when the engine finished with success or fail, and that can be with callbacks or notifications.
What is the difference between notification and callbacks it is another question, but 1:1 is faster the callback.

Event Dispacher in 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.

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.

Triggering events in Java when an object's state changes

I have an object in Java whose state changes over the course of time. When one of the fields in the object reaches a certain value, I want an external event to be triggered.
I know Swing handles this pattern through Listeners - and I am using Swing for this project - but I'm not sure what kind of Listener would apply to this case. The object's state is not being changed by the user, and Listeners seem to be triggered only by users' actions.
Edit: The object that I'm monitoring isn't itself a Swing component - it runs in the background in the main thread.
You might want to have a look at java.util.Observable, which is designed just for this purpose.
Here's a JavaWorld tutorial on Observer and Observable:
http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html
Whether that state is changed by the user or not really do not matter. You can invoke the listener callbacks from the method that changes the state and make sure that the state of the object could be changed only through that method:
class A {
public void changeState(State newState) {
state = newState;
for (SomeEventListenerInterface el : listeners) {
el.nofity(this, newState);
}
}
}
and Listeners seem to be triggered only by users' actions.
Not always. For example when you change the property of many Swing components (background, font, etc) a PropertyChangeEvent is fired.
I would suggest you can also use this event. Read the section from the Swing tutorial on How to Write a Property Change Listener for an example.

Categories