19 Aug 2008, 12:18

Eclipse/SWT - Context Menus on TreeViewers

Share

When trying to create context menus of SWT TreeViewers I didn’t find much documentation on that issue and the snippets I found were quite confusing. Here is an approach that did work out for me. Please note that there are other ways to achieve this as well. public class TreeView extends ViewPart { … public void createPartControl(Composite parent) { … this.initContextMenu(); } private void initContextMenu() { // initalize the context menu MenuManager menuMgr = new MenuManager(“#PopupMenu”); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { Action action = new Action() { public void run() { super.run(); // TODO do something } }; action.setText(“Title for Action”); manager.add(newEntry); } }); TreeViewer viewer = this.treeViewer; Menu menu = menuMgr.createContextMenu(viewer.getTree()); viewer.getTree().setMenu(menu); getSite().registerContextMenu(menuMgr, viewer); }