I\'m trying to display tooltips in Java which may or may not be paragraph-length. How can I word-wrap long tooltips?
This could be improved somewhat, but my approach was a helper function called before setting tooltip that split the tooltip text at provided length, but adjusted to break words on space where possible.
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class MultiLineTooltips
{
private static int DIALOG_TOOLTIP_MAX_SIZE = 75;
private static final int SPACE_BUFFER = 10;
public static String splitToolTip(String tip)
{
return splitToolTip(tip,DIALOG_TOOLTIP_MAX_SIZE);
}
public static String splitToolTip(String tip,int length)
{
if(tip.length()<=length + SPACE_BUFFER )
{
return tip;
}
List parts = new ArrayList<>();
int maxLength = 0;
String overLong = tip.substring(0, length + SPACE_BUFFER);
int lastSpace = overLong.lastIndexOf(' ');
if(lastSpace >= length)
{
parts.add(tip.substring(0,lastSpace));
maxLength = lastSpace;
}
else
{
parts.add(tip.substring(0,length));
maxLength = length;
}
while(maxLength < tip.length())
{
if(maxLength + length < tip.length())
{
parts.add(tip.substring(maxLength, maxLength + length));
maxLength+=maxLength+length;
}
else
{
parts.add(tip.substring(maxLength));
break;
}
}
StringBuilder sb = new StringBuilder("");
for(int i=0;i");
}
sb.append(parts.get(parts.size() - 1));
sb.append((""));
return sb.toString();
}
}
Use like
jComponent.setToolTipText(MultiLineTooltips.splitToolTip(TOOLTIP));