Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java, multiline tooltip with fixed max width, using html tag

I want to add multiline tooltip message to my swing component. The basic solution is to use html tags like this:

label.setToolTipText("<html><p width=\"350px\">" + text + "</p></html>");

It works fine with long text. But if the text, let's say, contains only one word it also will have fixed 350px width with a lot of empty space.


Is there any special html property for max-width which will work properly with setToolTipText() method? I tried the next solution but it doesn't work:

"<p style=\"max-width: 350px\">"

Should I calculate text width in pixels and change opening <p> tag if width lesser than 350 px?

like image 806
ferrerverck Avatar asked Nov 15 '13 18:11

ferrerverck


1 Answers

Following code will dynamically set the size of the tooltip.

If it is a single word, it will set the size according to the pixel size of the text. (There will be no empty space). If it is a large paragraph, it will expand up to 350 pixel max, and display the text in multiple lines.

FontMetrics fontMetrics = label.getFontMetrics(label.getFont());
int length = fontMetrics.stringWidth(text);
label.setToolTipText("<html><p width=\"" + (length > 350 ? 350 : length) + "px\">" + text + "</p></html>\"");

Screenshot - Tooltip: Single word

Screenshot - Tooltip: Multiple words

Screenshot - Tooltip: Paragraph

like image 163
Arindam Roy Avatar answered Oct 21 '22 04:10

Arindam Roy