Java examples for java.lang:String New Line
Wraps the line of text and add the new line(s) to list.
//package com.java2s; import java.awt.FontMetrics; import java.util.*; public class Main { /**/* ww w. jav a 2s .co m*/ * Wraps the line of text and add the new line(s) to <var>list</var>. * @param line A line of text to be wrapped * @param list The list of the wrapped lines * @param fm FontMetrics to measure the width of the strings * @param maxWidth Maximum width of the line(s) */ public static void wrapLineInto(String line, List<String> list, FontMetrics fm, int maxWidth) { int len = line.length(); int width; while (len > 0 && (width = fm.stringWidth(line)) > maxWidth) { // Guess where to split the line. int guess = len * maxWidth / width; // Try to split it at a space character between words. String before = line.substring(0, guess).trim(); width = fm.stringWidth(before); int pos; if (width > maxWidth) // The line is too long pos = findBreakBefore(line, guess); else { // The line is either too short or the required length pos = findBreakAfter(line, guess); if (pos != -1) { // Make sure this doesn't make it too long before = line.substring(0, pos).trim(); if (fm.stringWidth(before) > maxWidth) pos = findBreakBefore(line, guess); } } if (pos == -1) pos = guess; // Split in the middle of the word list.add(line.substring(0, pos).trim()); line = line.substring(pos).trim(); len = line.length(); } if (len > 0) list.add(line); } /** * Returns the index of the first whitespace character or '-' in <var>line</var> * that is at or before <var>start</var>. Returns -1 if no such character is found. * @param line A string of text * @param start Where to begin testing */ public static int findBreakBefore(String line, int start) { for (int i = start; i >= 0; --i) { char c = line.charAt(i); if (Character.isWhitespace(c) || c == '-') return i; } return -1; } /** * Returns the index of the first whitespace character or '-' in <var>line</var> * that is at or after <var>start</var>. Returns -1 if no such character is found. * @param line A string of text * @param start Where to begin testing */ public static int findBreakAfter(String line, int start) { int len = line.length(); for (int i = start; i < len; ++i) { char c = line.charAt(i); if (Character.isWhitespace(c) || c == '-') return i; } return -1; } }