MultiLine Label with auto adjust height.
Wrap text in Label
private void wrapLabelText(JLabel label, String text) {
FontMetrics fm = label.getFontMetrics(label.getFont());
PlainDocument doc = new PlainDocument();
Segment segment = new Segment();
try {
doc.insertString(0, text, null);
} catch (BadLocationException e) {
}
StringBuffer sb = new StringBuffer("<html>");
int noOfLine = 0;
for (int i = 0; i < text.length();) {
try {
doc.getText(i, text.length() - i, segment);
} catch (BadLocationException e) {
throw new Error("Can't get line text");
}
int breakpoint = Utilities.getBreakLocation(segment, fm, 0, this.width - pointerSignWidth - insets.left - insets.right, null, 0);
sb.append(text.substring(i, i + breakpoint));
sb.append("<br/>");
i += breakpoint;
noOfLine++;
}
sb.append("</html>");
label.setText(sb.toString());
labelHeight = noOfLine * fm.getHeight();
setSize();
}
Thanks,
Jignesh Gothadiya