KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > text > ConsoleParagraphFormatter


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.text;
5
6 import java.util.Arrays JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9
10 public class ConsoleParagraphFormatter implements ParagraphFormatter {
11
12   private final StringFormatter sf;
13   private final int maxWidth;
14
15   public ConsoleParagraphFormatter(int maxWidth, StringFormatter stringFormatter) {
16     this.maxWidth = maxWidth;
17     this.sf = stringFormatter;
18   }
19
20   public String JavaDoc format(String JavaDoc in) {
21     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
22     if (in == null) throw new AssertionError JavaDoc();
23     List JavaDoc words = parseWords(in);
24     int lineWidth = 0;
25     for (Iterator JavaDoc i = words.iterator(); i.hasNext();) {
26       String JavaDoc currentWord = (String JavaDoc) i.next();
27       if (lineWidth + currentWord.length() > maxWidth) {
28         if (lineWidth > 0) {
29           buf.append(sf.newline());
30         }
31         lineWidth = currentWord.length();
32       } else {
33         if (lineWidth > 0) {
34           buf.append(" ");
35         }
36         lineWidth += currentWord.length();
37       }
38       buf.append(currentWord);
39     }
40     return buf.toString();
41   }
42
43   private List JavaDoc parseWords(String JavaDoc in) {
44     String JavaDoc[] words = in.split("\\s+");
45     return Arrays.asList(words);
46   }
47
48 }
49
Popular Tags