Saturday, April 18, 2009

Add Menu to Header of Tab Item in GXT

I want to add Context Menu to the Header of the TabItem under Ext-Gwt (GXT). Unfortunately i can't find any proper method for me to do that. The Header Item of Ext-GWT tab item was packaged protected and I couldn't override or extend it.

After research for some time, I find out another way to add context menu to header of the tab item. The example below shows the basic step to add the context menu into tabitem header.


First of all, I prepare a menu item and add appropriate listener to it.

MenuItem closeMenuItem = new MenuItem();
closeMenuItem.setText("Close");
closeMenuItem.addSelectionListener(new SelectionListener(){
@Override
public void componentSelected(MenuEvent ce){
this.close();
}
});


Then the next step, i instance a Menu and add previous menu item into it.
final Menu contextMenu = new Menu();
contextMenu.add(closeMenuItem);


Last part here I try to listen the mouse up event and check whether the click is the right click.
Stop the right click default action by calling stopEvent(), and show the context menu at the location.
tabItem.getHeader().addListener(Events.OnMouseUp, new Listener(){
public void handleEvent(ComponentEvent event){
if(event.isRightClick()){
event.stopEvent();
contextMenu.showAt(event.getClientX(), event.getClientY());
}
}
});


Please take note for some browsers, i don't know why the event.stopEvent() cannot function properly to stop the default action of the right click, then you need to add
<body oncontextmenu="return false;">

in your main html file.

No comments: