Here you can find the source of splitText(String text, String delim, FontMetrics fontMetrics, int width)
Parameter | Description |
---|---|
text | The text to split. |
delim | Characters to consider as word delimiting. |
fontMetrics | <code>FontMetrics</code> used to calculate text width. |
width | The text width maximum. |
public static List<String> splitText(String text, String delim, FontMetrics fontMetrics, int width)
//package com.java2s; /**/* w w w . j av a 2 s . co m*/ * Copyright (C) 2002-2015 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ import java.awt.FontMetrics; import java.util.ArrayList; import java.util.List; public class Main { /** * Split some text at word boundaries into a list of strings that * take up no more than a given width. * * @param text The text to split. * @param delim Characters to consider as word delimiting. * @param fontMetrics <code>FontMetrics</code> used to calculate * text width. * @param width The text width maximum. * @return A list of split text. */ public static List<String> splitText(String text, String delim, FontMetrics fontMetrics, int width) { List<String> result = new ArrayList<>(); final int len = text.length(); int i = 0, start; String top = ""; Character d = null; for (;;) { for (; i < len; i++) { if (delim.indexOf(text.charAt(i)) < 0) break; } if (i >= len) break; start = i; for (; i < len; i++) { if (delim.indexOf(text.charAt(i)) >= 0) break; } String s = text.substring(start, i); String t = (top.isEmpty()) ? s : top + d + s; if (fontMetrics.stringWidth(t) > width) { if (top.isEmpty()) { result.add(s); } else { result.add(top); top = s; } } else { top = t; } if (i >= len) { if (!top.isEmpty()) result.add(top); break; } d = text.charAt(i); } return result; } }