Search code examples
javacontextmenue4treeviewer

How can we generate a sub menu context dynamically for a treeviewer


I have populated a context menu for a treeviewer but now i need to dynamically populate the submenu context for the treeviewer the sub context menu shold contain all the contents in the list.for eg the list contains [a,b,c,d,e] so now main menu has menu A and the submenu must contain all the elements in the list can this be done

the menu structure should be as follows A->a b c d e

Now the code for context menu is as follows

protected void fillContextMenu(final IMenuManager contextMenu) {
        //String nnn = null;
        //contextMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
        //contextMenu.add(new GroupMarker(nnn));

         IMenuManager submenu = new MenuManager("Add Test Case");

            submenu.add(new Action("Sub menu item 1") {
                 @Override
                 public void run() {
                     // implement this
                 }
             });

           contextMenu.add(submenu);



        contextMenu.add(new Action("Add Test step") {
            @Override
            public void run() {
                // don't do anything here
            }
        });
        contextMenu.add(new Action("Add New Test Case") {
            @Override
            public void run() {
                // implement this
            }


        });

}

So now how can we generate the dynamic sub context menu contained in the list.


Solution

  • First make sure that

    IMenuManager.setRemoveAllWhenShown(true);
    

    is called when you create the context menu. This means that fillContextMenu will be called each time the menu is shown.

    Then all you need to do is loop through the list creating actions for each item in the list in fillContextMenu:

    List<String> itemList = .... your list
    
    for (String item : itemList)
     {
       submenu.add(new Action(item) {
             @Override
             public void run() {
                   // implement this
             }
       });
     }