Wrap JLabel Text
Posted by david | Filed under Java, Technical Tidbits
It took a bit of experimentation, but I think this routine could be used to allow a Java JLabel component to contained wrapped text.
This routine depends on the ability for JLabel text to contain HTML.
Basically it iterates through each word in the JLabel text, appends the word to a ‘trial’ string buffer, and determines if the trial string is larger than the JLabel’s container. If the trial string is larger, then it inserts a html break in the text, resets the trial string buffer, and moves on to the next word.
private void wrapLabelText(JLabel label, String text) { FontMetrics fm = label.getFontMetrics(label.getFont()); Container container = label.getParent(); int containerWidth = container.getWidth(); BreakIterator boundary = BreakIterator.getWordInstance(); boundary.setText(text); StringBuffer trial = new StringBuffer(); StringBuffer real = new StringBuffer("<html>"); int start = boundary.first(); for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) { String word = text.substring(start,end); trial.append(word); int trialWidth = SwingUtilities.computeStringWidth(fm, trial.toString()); if (trialWidth > containerWidth) { trial = new StringBuffer(word); real.append("<br>"); } real.append(word); } real.append("</html>"); label.setText(real.toString()); }
September 10th, 2005 at 4:03 pm
The best solution I’ve ever seen for wrapping label text.
One suggestion: you may want to pass a ‘width’ parameter into the method, instead of using the parent container’s width. That would be useful when designing complex user interface, where you can decide the label width based on the preferred sizes of neighboring components.
January 12th, 2006 at 2:13 pm
Thanks for a good method. I tried to use it until I found that JLabels automatically wrap for you if you simply surround your text with the opening and closing html tags.
February 9th, 2006 at 6:50 pm
Thanks for the html tags tip. That made my day.
October 6th, 2007 at 7:34 pm
For anyone who wants simple code for this, see the snippet at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4348815 . Works a treat.