Ava
Ava

Reputation: 2132

Get SWT widget at location

I have a set of x/y coordinates relative to a composite, how do find what widget those coords fall in?

Upvotes: 3

Views: 1620

Answers (1)

l1sq0u48
l1sq0u48

Reputation: 381

It's quite ugly but you can do a function like this :

public Control getControl(Composite composite, int x, int y)
{
  Control control = null;
  Control[] children = composite.getChildren()
  if (children.length == 0)
     control = composite;
  else
    for (Control tmp : children) {
       // The check below will not work because x, y and the control's bounds could be
       // relative to different parents... Better to convert all coordinates to display
       // by using Control.toDisplay() and then compare below
       if (tmp.getBounds().contains(x, y)) 
       {
         if (control instanceof Composite)
             control = getControl(tmp, x, y);
         else
             control =  tmp;
         break;
       }

    }

  return control;
}

If you get the coordinates using a MouseListener, you can simply use :

event.getSource();

Upvotes: 5

Related Questions