
Saturday October 14, 2006
TIP: Multiline tooltip
Say you want to display the message from a Throwable in a JLabel and the Throwable's stack trace in the label's tootip - you could do something like the code below:
From the GUI standards point of view this may not be a good practice because the tooltip text is not selectable/copyable. I am using the contrived example only to demonstrate the tip. In fact I wish the Swing tooltip had a mode in which the tooltip text could be selected/copied.
Throwable throwable = new Throwable("Sample message from a Throwable");
JLabel messageLabelWithSingleLineTooltip = ...; StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter)); // capture the stack trace as a string
messageLabelWithSingleLineTooltip.setText(throwable.getMessage() + "(Single line tooltip)");
messageLabelWithSingleLineTooltip.setToolTipText(
stringWriter.toString()
);
You get the following wide, single line tooltip (truncated to keep the image size small).

Not very useful. The stack trace is very hard to read. The problem happens because normally the tooltip text is shown as a single line of text where as the stack trace is in the form of a multiline text. The newlines are simply stripped off. There is a simple solution to the problem though. The Swing tooltip supports html syntax. Thus you can use "<html><pre>" + multilineText + "</pre>" and let the <pre> tag handle the multiline text. Here is the code:
JLabel messageLabelWithMultiLineTooltip = ...;
messageLabelWithMultiLineTooltip.setText(throwable.getMessage() + "(Multiline tooltip)");
messageLabelWithMultiLineTooltip.setToolTipText(
"<html><pre>"
+ stringWriter.toString()
+ "</pre>"
);
With the above code you get: multil line tooltip as shown below:

For the details of html support in Swing components see: Using HTML in Swing Components. A lot of interesting things can be done with this functionality.
If you want to play with code here is a Netbeans 5.5 project.
DISCLAIMER: This code is experimental. So no guarantees. Use the code at your own risk.
Also see TIP: Images in Tooltips blog entry which is based on the same technique.
Posted by sandipchitale
( Oct 14 2006, 05:42:48 PM PDT ) Permalink
Trackback URL: http://blogs.sun.com/scblog/entry/tip_show_mutiline_text_in
Posted by David Havrda on January 26, 2007 at 12:38 PM PST #
It’s very good article. Great site with very good look and perfect information. I like it too.
Posted by mckay on June 03, 2008 at 08:07 AM PDT #