Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

The problem of providing a customized context-menu on right-click in HTML are an old hat, as this example from 2002 (sic!) demonstates, but solving this problem in GWT is still a major operation.. or is it?

Googling for "gwt context menu" produces a host of "solutions" to the problem, notably most of them at least two years old. They mostly involve registering a DOM event-listener for the oncontextmenu event, more or less manually, and at least one custom class.
What they all miss is that google silently introduced the ContextMenuEvent (possibly as early as 2008), a DomEvent, which offers an unspectacularly painless solution to the problem. Just implement the handler and add it to the widget you want to use it in (if need be you can do this using addDomHandler() directly, although arguably this is not in good style) - finished!

Judging by the age of the postings on this issue, by now most people have found a solution that works for them. However it may not be the simplest...

The simplest way of implementing a custom context menu is certainly the following:

Code Block
class MyWidget extends Composite implements ContextMenuHandler {
  
  // just an example, use a meaningful Widget here...
  private Widget base;

  private PopupPanel contextMenu;


  public MyWidget() {
    // initialize base widget, etc...

    this.contextMenu = new PopupPanel(true);
    this.contextMenu.add(new HTML("My Context menu!"));
    this.contextMenu.hide();

    initWidet(this.base);

    // of course it would be better if base would implement HasContextMenuHandlers, but the effect is the same
    addDomHandler(this, ContextMenuEvent.getType());
  }


  public onContextMenu(ContextMenuEvent event) {
    // stop the browser from opening the context menu
    event.preventDefault();
    event.stopPropagation();


    this.contextMenu.setPopupPosition(event.getNativeEvent().getClientX(), event.getNativeEvent().getClientY());
    this.contextMenu.show();
  }

}