Thursday, July 24, 2014

Context Menu or Right Click Handler in GWT

Context menu is one of the strange thing to deal with it and hard to implement it also. In this post let see how we deal with right click menu for browser (means whole application) and for a single widget in browser. The below steps shows how to implement a basic context menu aka right click menu.
  • Create a menu of what you are trying to show.
  • Take a Popup Panel. And add your menu to that Popup Panel.
  • Just place the handler to the Root-panel which is going to fire when user right click's on the browser.
Lets implement the same points in code and see how it goes.
 rootPanel.sinkEvents(Event.ONCONTEXTMENU);
 rootPanel.addHandler(
     new ContextMenuHandler() {@
         Override
         public void onContextMenu(ContextMenuEvent event) {
             event.preventDefault();
             event.stopPropagation();
             popupMenu.setPopupPosition(event.getNativeEvent().getClientX(),
                 event.getNativeEvent().getClientY());
             popupMenu.show();
         }
     }, ContextMenuEvent.getType());
The above code tweaks the right click handler and shows the custom pop up menu on right click of right click. And if you want to show custom right click menu for a single widget, the below code shows it how.
 lable.sinkEvents(Event.ONCONTEXTMENU);
lable.addHandler(
    new ContextMenuHandler() {@
        Override
        public void onContextMenu(ContextMenuEvent event) {
            event.preventDefault();
            event.stopPropagation();
            popupMenu.setPopupPosition(event.getNativeEvent().getClientX(),
                event.getNativeEvent().getClientY());
            popupMenu.show();
        }
    }, ContextMenuEvent.getType());
That is all to do show context menu for specific label or any other widget referred.

Next >> Multiple inheritance in interface supports in Java 

No comments:

Post a Comment