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);
}
Thank you for sharing… this saved my day
a small mistake in the code:
replace
manager.add(newEntry);
with
manager.add(action);