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 thoughts on “Wrap JLabel Text

  1. 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.

    Reply
  2. 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.

    Reply

Leave a Reply

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