Java FontMetrics wrapText(String text, int width, FontMetrics fontMetrics)

Here you can find the source of wrapText(String text, int width, FontMetrics fontMetrics)

Description

wrap Text

License

Open Source License

Declaration

public static List<String> wrapText(String text, int width, FontMetrics fontMetrics) 

Method Source Code


//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;
        }
    }
}

Related

  1. splitText(String text, String delim, FontMetrics fontMetrics, int width)
  2. stringByTruncatingToFitInWidth(String s, int width, Graphics g, String truncatedSuffix)
  3. stringDimension(Graphics g, Font f, String s)
  4. StringDimension(Graphics g, String text)
  5. wordWrap(String text, FontMetrics metrics, double width)