views:

246

answers:

1

Hi all,

I attached a listener to the Shell on SWT.MouseUp and SWT.MouseDown events, but the handleEvent method never gets fired. I tried clicking at many places on the window, but it doesn't get even to the System.out.println(..) in the code below...

Do you spot any error here?

Thank you!

//c is a Composite.

final Listener l = new Listener(){
public void handleEvent(Event event) {
System.out.println("Got event. "+event);
Rectangle rect = c.getBounds();
if (rect.contains(event.x, event.y)){
 if((Boolean)c.getData("selected")){
  c.setData("selected", Boolean.FALSE);
 }else{
  c.setData("selected", Boolean.TRUE);
 }
}
}
};
c.getShell().addListener(SWT.MouseUp, l);
c.getShell().addListener(SWT.MouseDown, l);

(This composite is inside an Eclipse editor that uses the Forms Toolkit)

Regards,

-Pradyumna

+2  A: 

By writing

c.getShell().addListener(SWT.MouseUp, l);
c.getShell().addListener(SWT.MouseDown, l);

you add the listeners to the shell only! Clicking on a child of the shell does not trigger an event for c.getShell(). Try to click near the border of the window and watch out for your trace message.

If you want to get events for the clicks on c, you have to add listeners to c via c.addListener(.). If you do that, you won't need the condition rect.contains(event.x, event.y) because you know, that the click happened on c.

the.duckman
Thank you. I get the idea now.. but is there a way we can hook up a listener to a composite that gets fired when the event (such as MouseDown) happens on any descendant of that composite?
Pradyumna
You could iterate through the `getChildren()` of a composite and add the listeners to each.
Paul Lammertsma
Something worth mentioning might be `Display.addFilter(.)`: You get notified about any event in the Display's event loop. This is not exactly what you are asking about, and in most cases this is not the proper way of doing things, but in some rare occasions it comes really handy.
the.duckman