SWT Tree and tooltips

26. December, 2009

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.