Search code examples
javaeclipse-rcprcpe4nattable

E4 NatTable dynamic context menu


I want the context menu items of my natTable to change, depending on the selected row. How can I achieve this ?

UPDATE: this works so far, i have A and B showing on even/uneven lines. My next question is: does this mean that I have to call these methods for every menu item groups ?

myPopupMenuBuilder.withMenuItemProvider("A", new IMenuItemProvider() {
        @Override
        public void addMenuItem(NatTable paramNatTable, Menu paramMenu) {
            MenuItem row = new MenuItem(paramMenu, SWT.PUSH);
            row.setText("A");
        }
    }).withMenuItemProvider("B", new IMenuItemProvider() {
        @Override
        public void addMenuItem(NatTable paramNatTable, Menu paramMenu) {
            MenuItem row = new MenuItem(paramMenu, SWT.PUSH);
            row.setText("B");
        }
    }).withVisibleState("A", new IMenuItemState() {
        @Override
        public boolean isActive(NatEventData paramNatEventData) {
            return paramNatEventData.getRowPosition() % 2 == 0;
        }
    }).withVisibleState("B", new IMenuItemState() {
        @Override
        public boolean isActive(NatEventData paramNatEventData) {
            return paramNatEventData.getRowPosition() % 2 == 1;
        }
    });

Solution

  • It depends on how you implement the context menu. If you use the NatTable way of registering a context menu (which I typically suggest) you can use PopupMenuBuilder#withEnabledState() or PopupMenuBuilder#withVisibleState(). Inside the implementation of IMenuItemState you get the position where the click was performed, which then can be used to get the underlying data.

    More information can be found in my blog post about that topic: NatTable context menus with Eclipse menus

    If you want to use E4 menus, you will have to implement some additional logic to extract the necessary information from the click with regards to the NatTable.