Daily Archives: 30-June-2005

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