Eclipse provides the capability to specify custom context menus and add them via extension points.
Furthermore, it is possible to add a context menu to your self implemented viewer. There are several tutorials out there how this is done.
However, most of them describe how programatically contribute to or activate a context menu which includes actions from other plugins as well. If you want to really focus on the actions you intend to have in your viewer, it requires even less code but you have to know which one.

Below, you can find an example code snippet how to contribute your action:

private void initSimpleContextMenu() {

  MenuManager menuMgr = new MenuManager();
  menuMgr.addMenuListener(new IMenuListener() {

    public void menuAboutToShow(IMenuManager manager) {

      // initialize the action to perform
      Action action = new Action() {

        public void run() {
          // the action code
          System.out.println("Hello World");
      action.setText("Hello World");
  Menu menu = menuMgr.createContextMenu(variationPointTreeViewer.getTree());

In the example, the creation of the context menu is encapsulate in a method “initSimpleContextMenu()”. This is done to keep the code clean, but does not have to. The method, should be called after the viewer, it should be attached to has been created.
For example after the myTreeViewer creation in this example:

myTreeViewer = new TreeViewer(this, SWT.BORDER);
myTreeViewer.setLabelProvider(new ViewerLabelProvider());
myTreeViewer.setContentProvider(new TreeContentProvider());


Please note, that the example contains a tree viewer, but could also be used for other viewers such as TableViewers or whatever. You just need to create the appropriate type of viewer, and add the menu to the appropriate inner component of the viewer. (e.g. “myTableViewer.getTable().setMenu(menu);” instead of “myTreeViewer.getTree().setMenu(menu);”)

Eclipse: Add a Simple Context Menu to Custom Viewer

Post navigation

Leave a Reply