Thursday, September 16, 2010

GWT: Custom context menu on a Tree

Monkeys, in order to add a custom pop up menu to a tree (or any similar widget I suppose) which is displayed instead of the usual browser's context menu when you right-click on the tree, you can do the following:

Create a Tree class that implements the correct interface for adding a context menu handler:
package com.tradecraft.property.web.client.view.type;

import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.HasContextMenuHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Tree;

public class MenuContextTree extends Tree implements HasContextMenuHandlers {

  @Override
  public HandlerRegistration addContextMenuHandler(ContextMenuHandler handler) {
    return addDomHandler(handler, ContextMenuEvent.getType());
  }

}

Then add a handler instance to your tree:
public class PropertyTypesAdminScreen extends BaseClientContentScreen {
  ...
  @Override
  public void initScreenUi() {
    tree = new MenuContextTree();
    tree.addContextMenuHandler(new ContextMenuHandler() {      
      @Override
      public void onContextMenu(ContextMenuEvent event) {
        showContextMenu();
        //Don't let the browser display its default context menu
        event.preventDefault();
      }
    });
    mainPanel.add(tree);
  }

  private void showContextMenu() {
    TreeItem selectedTreeItem = tree.getSelectedItem();
    if (selectedTreeItem != null && selectedTreeItem.getUserObject() != null) {
      //do your thing like display a pop up menu
      MenuDialog menuDialog = new MenuDialog(menuBar);
      menuDialog.showRelativeTo(selectedTreeItem);
    }
  }
}


1 comment:

  1. By default right click does not select an item in a tree. So this code will only work if an tree item is first selected and then a right click is performed. If right click is done without selection then context menu is shown on previously selected tree item.

    Thanks,
    Srini

    ReplyDelete