Search code examples
eclipseswtjfacercpe4

How to create a custom SWT Tooltip using JFACE for an RCP MDirectToolItem?


I would like to create a custom tooltip for an RCP MDirectToolItem or MHandledToolItem. JFace provides the org.eclipse.jface.window.ToolTip class, which I can extend and override the createToolTipContentArea() method. However, to instantiate a JFace ToolTip, I have to give it the SWT Control that will use the ToolTip. I cannot figure out a way to get the underlying SWT Control from the MDirectToolItem.

I have been able to get the MToolBar and the MDirectToolItem (which I defined in the Application.e4xmi) using the EModelService.find() method. I tried getting the underlying SWT Control from the MDirectToolItem, but it does not appear there is a way to do that.

I also tried creating an SWT ToolItem and adding it to the MToolBar, but the children of the MToolBar are only MToolBarElement's.


Solution

  • Tool items don't have a separate control, they are part of the parent ToolBar control. The SWT ToolItem class represents the tool item, this is just derived from Widget rather than Control.

    So you will have to set the tool tip on the tool bar control and work out which tool item is active when the tool tip is shown.

    The application model classes which represent UI objects all extend the MUIElement interface. This provides a getWidget method to get the UI object.

    So for MToolBar you can do:

    ToolBar toolbar = (ToolBar)mtoolbar.getWidget();
    

    and for MToolItem (either handled or direct) you can do:

    ToolItem toolitem = (ToolItem)mtoolitem.getWidget();
    

    If you create the ToolTip with the NO_RECREATE style it will call the getToolTipArea method to determine if the tool tip need to be changed. You can use something like the following to have a different area for each tool item:

    @Override
    protected Object getToolTipArea(final Event event)
    {
      // TODO save the ToolBar in the class as 'toolBar'
      ToolItem item = toolBar.getItem(new Point(event.x, event.y));
      if (item != null)
        return item;
    
      return super.getToolTipArea(event);
    }