SWT Tree and tooltips

If you need tooltips for elements in an SWT Tree or JFace TreeViewer, you had to jump through some hoops as Snippet 125 shows.

Since SWT/JFace 3.3, you should use a TreeViewer, a ColumnLabelProvider (which has all those cool getTooltip() methods) and this line of code:

ColumnViewerToolTipSupport.enableFor (viewer);

That’s it. There is a catch, though: The tooltip doesn’t wrap automatically. If you have long lines of text, you need commons-lang and this piece of code:

    private String wrap (String s)
    {
        StringBuilder buffer = new StringBuilder ();
        
        String delim = "";
        for (String line: s.trim ().split ("\n"))
        {
            buffer.append (delim);
            delim = "\n";
            buffer.append (WordUtils.wrap (line, 60, "\n", true));
        }
        
        return buffer.toString ();
    }

Note that this code is only necessary if you have several lines of text in the tooltip. For single long lines, WordUtils.wrap() alone is enough.

Link to the JFace snippet.

2 Responses to SWT Tree and tooltips

  1. MUSTAKAHMMAD M says:

    Nice. This will help to wrap the text. What if the text in length is huge (vertically), are we going to get scroll bars ?

    • digulla says:

      I don’t know. It’s been a while since I used SWT. I don’t think scrollbars are added automatically.

      That said, tooltips are for small amounts of text. If you have a long test, they are the wrong tool. You should use a popup of some kind instead (button plus new window with proper UI).

      If you need scrollbars, try to override ColumnViewerToolTipSupport.createToolTipContentArea() to create a more complex layout.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.