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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s