Here you can find the source of wrapText(String text, int width, FontMetrics fontMetrics)
public static List<String> wrapText(String text, int width, FontMetrics fontMetrics)
//package com.java2s; import java.awt.*; import java.util.*; import java.util.List; public class Main { public static List<String> wrapText(String text, int width, FontMetrics fontMetrics) { LinkedList<String> lines = new LinkedList<String>(); if (isEmpty(text)) { lines.add(text);/*from w ww. ja v a 2 s . c o m*/ return lines; } text = removePostfixedNewline(text); if (!text.contains("\n") && fontMetrics.stringWidth(text) <= width) { lines.add(text); return lines; } for (String line : text.split("\n")) { StringBuilder currentLine = new StringBuilder(); for (String word : line.split(" ")) { if (fontMetrics.stringWidth(currentLine.toString() + word) > width) { lines.add(currentLine.toString()); currentLine = new StringBuilder(); } currentLine = currentLine.append(word).append(" "); } if (!isEmpty(currentLine.toString())) { lines.add(currentLine.toString()); } } return lines; } public static boolean isEmpty(String str) { return str == null || "".equals(str.trim()); } public static boolean isEmpty(List list) { return list == null || list.size() == 0; } public static boolean isEmpty(StringBuilder sb) { return sb == null || isEmpty(sb.toString()); } public static String removePostfixedNewline(String s) { if (isEmpty(s)) { return s; } else { return s.endsWith("\n") ? s.substring(0, s.length() - 1) : s; } } }