What is an EventListener unlike an EventHandler?

How can I implement it? Will it work across multiple builds? If not, how can I make it work?

+4
source share
1 answer

In order not to fully understand this question, I would like to offer another possible explanation.

Speaking of classes, Java has an EventListener , and .NET has an EventHandler . Both have the same goal: handling events. However, there are differences in implementation. You can say that .NET event processing is a higher level of abstraction for Java event listeners.

The Java EventListener is a "tagging interface that should extend all event listener interfaces" (ie MouseListener) .. NET EventHandler is a delegate, a strongly typed pointer to a method that processes the event.

More broadly, an event listener is an object that implements an interface for handling events, while an event handler is just a method that processes an event. Generally speaking, event listeners implement an observer design pattern , and event handlers hide all the plumbing of this pattern. Therefore, recording an event listener is much more complex and tends to be more verbal than recording an event handler .

I would recommend Microsoft read the observer design template to better understand it.

So, to implement an event handler, you simply assign a delegate to the event of the object you want to handle. I.e.

Button.Click += new EventHandler(MyButton_Click); 

where MyButton_Click is a method (it can be in your class or somewhere else) that has an EventHandler signature and actually processes the event, i.e.

 private void MyButton_Click(object sender, EventArgs e) { doSomething(); } 

To achieve the same result with event listeners in Java, you should write something like this (forgive me if I am wrong, as I am writing it from memory):

 public class MyClass { Button myButton; MyClass() { ... myButton.addMouseListener(new ButtonHandler()); } public class ButtonHandler implements MouseListener { public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) { doSomething("Mouse clicked", e); } } } 

Naturally, there are many ways to implement this common observer pattern, including implementing EventListener interfaces in the class itself, in inner classes, in anonymous classes, in adapters, etc. But this should demonstrate the essence.

+11
source

All Articles