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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With