Search code examples
javaimageswttooltip

Java SWT: show paintings in tooltip


I want to set tooltip for StyledText in Java SWT. The idea is to show information for the text where the mouse clicks. Up to now I can only show text in the tooltip, but I want the whole tooltip to be an image, which is painted using drawing methods in SWT to show some structure in the information. It seems Tooltip won't handle that, so could anyone suggest me how to do that, or with which widget I can achieve it?

Edit: How can I set the size of the composite which createToolTipContentArea returns?

protected Composite createToolTipContentArea(Event event, Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.addPaintListener(new SPPaintListener());
composite.setSize(680, 600);

return composite;
}
private class SPPaintListener implements PaintListener {

public void paintControl(PaintEvent e) {

  drawLyrics(e);
  e.gc.dispose();
}
}

private void drawLyrics(PaintEvent e) {
e.gc.setAntialias(SWT.ON);

Font font = new Font(e.display, "Purisa", 10, SWT.NORMAL);
Color color = new Color(e.display, 25, 25, 25);

e.gc.setForeground(color);
e.gc.setFont(font);

e.gc.drawText("em so transitory", 20, 30);
e.gc.drawText("em so transitory", 180, 30);
e.gc.drawText("Theermanent one", 20, 60);
e.gc.drawText("Theermanent one", 180, 60);

e.gc.drawLine(10, 30, 15, 30);

font.dispose();
}

like said, I need some paintings on the composite, but they won't get shown fully.


Solution

  • You can use a class derived from org.eclipse.jface.window.ToolTip to draw anything you like in a tooltip.

    public class MyToolTip extends ToolTip
    {
      public MyToolTip(Control control)
      {
        super(control, NO_RECREATE, false);
      }
    
      @Override
      protected Composite createToolTipContentArea(final Event event, final Composite parent)
      {
        // TODO add your controls here
      }
    }
    

    Use with:

    new MyToolTip(control);
    

    where control is the control that should have the tooltip.

    I have shown the simplest form where the tooltip area is the same for the whole control. You can also override the getToolTipArea method to change the tooltip depending on the position in the control.

    For an image the createToolTopArea might look like:

    @Override
    protected Composite createToolTipContentArea(final Event event, final Composite parent)
    {
      Composite body = new Composite(parent, SWT.NONE);
    
      body.setLayout(new GridLayout());
    
      Label label = new Label(body, SWT.LEAD);
    
      Image image = ... your image
    
      label.setImage(image);
    
      return body;
    }