views:

557

answers:

2

I'm capturing a right click event to show a context menu. What I haven't been able to figure out, is how to make the right click actually select the TreeItem, prior to showing of context menu.

All help is appreciated.

 private Tree tree = new Tree() {
  @Override
  public void onBrowserEvent(Event event) {   
    if (event.getTypeInt() == Event.ONCONTEXTMENU) {
     DOM.eventPreventDefault(event);          
     showContextMenu(event);
    }   
   super.onBrowserEvent(event);
  }

  @Override
  protected void setElement(Element elem) {
   super.setElement(elem);
   sinkEvents(Event.ONCONTEXTMENU);
  }

 };
+1  A: 

ONMOUSEDOWN event gets fired before ONCONTEXTMENU. Have you tried to listen for onMouseDown events, and set the selected item? Something along these lines:

@Override
public void onBrowserEvent(Event event) {   
switch (DOM.eventGetType(event)) {
    case Event.ONMOUSEDOWN:
        if (DOM.eventGetButton(event) == Event.BUTTON_RIGHT) {
            TreeItem selectedItem = findSelectedItem(event);
            if (selectedItem != null) {
                selectedItem.setSelected(true);
            }
        } else {
            super.onBrowserEvent(event);
        }
        break;
    case Event.ONCONTEXTMENU:
        showContextMenu(event);
        break;
    default:
        super.onBrowserEvent(event);
        break;
    }

and findSelectedItem traverses the tree looking for the selected item:

TreeItem findSelectedItem(Event e) {
    return findSelectedItemRecursive(event.getClientX(), event.getClientY());
}

TreeItem findSelectedTreeItemRecursive(TreeItem root, int x, int y) {
    if (null == root) {
        int count = getItemCount();
        for (int i = 0; i < count; i++) {
            TreeItem selected = findSelectedTreeItemRecursive(getItem(i), x, y);
            if (selected != null) {
               return selected;
            }
        }
        return null;
    }
    int count = item.getChildCount();
    for (int i = 0; i < count; i++) {
        TreeItem selected = findSelectedTreeItem(item.getChild(i), x, y);
        if (selected != null) {
            return selected;
        }
    }

    if (x >= item.getAbsoluteLeft()
        && x <= item.getAbsoluteLeft() + item.getOffsetWidth()
        && y >= item.getAbsoluteTop()
        && y <= item.getAbsoluteTop() + item.getOffsetHeight()) {
        return item;
    }
    return null;
}
milan