TIP: Multiline tooltip
By sandipchitale on Oct 14, 2006
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)");
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)");
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.