Reputation: 151
Please help me understand the difference between handleEvent
of Listener
interface versus <Selection/Key/Focus>Event
of <Selection/Key/Focus>Listener
interfaces . Thanks in Advance.
I have come across handleEvent
method with Event
parameter where the usage is SWT.FocusIn
or SWT.FocusOut
for Listener
Interface. And then there is also focusGained
/focusLost
FocusEvent
parameter.
Similarly it is the same with SWT.Selection
used in handleEvent
method and then there is also keyPressed
/keyReleased
KeyEvent
of KeyListener
Interface.
Similarly it is the same with SWT.KeyDown
or SWT.KeyUp
used in handleEvent
method and then there is also widgetSelected
/widgetDefaultSelected
SelectionEvent
of SelectionListener
Interface.
These appear to me as same/duplicate. Is there any difference or reason why we should use one versus other?
Upvotes: 1
Views: 864
Reputation: 36894
What you discovered there are typed and untyped events.
As you already found out, there is a connection. The typed events are the ones that look like this:
button.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(SelectionEvent e) {}
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
});
Whereas the untyped events look like this:
button.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event e) {}
});
If you look at the source of Button
, you will see this:
public void addSelectionListener (SelectionListener listener) {
checkWidget();
if (listener == null) error(SWT.ERROR_NULL_ARGUMENT);
TypedListener typedListener = new TypedListener(listener);
addListener(SWT.Selection, typedListener);
addListener(SWT.DefaultSelection, typedListener);
}
As you can see, addSelectionListener
just calls addListener
.
Concluding: It is kind of redundant, but it makes the source more usable. If you want to take care of all the cases that have to do with selection, add the SelectionListener
. If you just want to take care of SWT.Selection
, aadd the Listener
.
It really is a matter of taste. I prefer to add the untyped event listeners, because I find myself often not using all the methods of a SelectionListener
or a MouseListener
when I only want to take care of one event.
Finally: Here is something to read if you want to know more (and have a mapping between typed and untyped events).
Especially this part:
In early versions of SWT, there were only untyped listeners. After considerable discussion between the Eclipse implementers, the SWT user community, and the developers, it was decided to include a more "JavaBeans-like" listener mechanism. It was felt that this would ease the transition to SWT for developers who were already familiar with AWT/Swing. The untyped listeners remain as the implementation mechanism for event handling in SWT. The typed listeners are defined in terms of them.
Upvotes: 3