RIght-Click in GWT?

Soren Johnson picture Soren Johnson · Sep 16, 2009 · Viewed 7.8k times · Source

I am building an AJAX web app with GWT, and I want to use right-click for various things, just like in a desktop app. However, right-click produces the standard Web context menu and void onClick(ClickEvent event) never gets called. Has anyone figured out how to get this to work? thanks!

Answer

1-14x0r picture 1-14x0r · Aug 6, 2012

easy peasy, add a listener on the contextmenuhandler which will display a widget based on where the user right clicks. https://confluence.clazzes.org/pages/viewpage.action?pageId=425996

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();

    initWidget(this.base);

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


  public void 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();
  }

}

lastly you will want to disable the browsers menu for full overloading of this type of context menu. That should work in all of the browsers except opera. but honestly who uses that these days neways ^_______^

<body oncontextmenu="return false;">