«

»

Jun 30 2005

Print this Post

Wrap JLabel Text

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());
}

4 comments

Skip to comment form

  1. Pete

    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.

  2. biff

    Thanks for the html tags tip. That made my day.

  3. Brian Mauter

    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.

  4. Mace

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

css.php