gwtcontextmenugwt-celltable

Different ContextMenus for GWT CellTable header and body


I've been browsing Stackoverflow for an hour now and I just can't find an answer, that's exactly what I need.

Currently we are using a CellTable to display some data. The first row of the table is, of course, the header. When right-clicking anywhere on this table, a context menu is opened. My client now wishes to have a few additional options in this context menu, but only when clicking on the header. I am currently stuck with trying to figure out whether the right click originated from the header or the table body.

if ( contextMenu == null )
        {
            contextMenu = new ContextMenu();

            table.sinkEvents(Event.ONCONTEXTMENU);
            table.addHandler(new ContextMenuHandler()
            {

                @Override
                public void onContextMenu(ContextMenuEvent event)
                {
                    //here I'd like to check if the clicked row index == 0 and display a different context menu
                    event.preventDefault();
                    event.stopPropagation();
                    contextMenu.setPopupPosition(event.getNativeEvent().getClientX(), event.getNativeEvent().getClientY());
                    contextMenu.setAutoHideEnabled(true);
                    contextMenu.show();
                }
            }, ContextMenuEvent.getType());
        }

Solution

  • Use HeaderBuilder's isHeader() method:

    public void onContextMenu(ContextMenuEvent event) {
    
        // ...
    
        EventTarget eventTarget = event.getNativeEvent().getEventTarget();
        Element element = eventTarget.cast();
        if(table.getHeaderBuilder().isHeader(element))
            // display context menu for header
        else
            // display context menu for body
    }