KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > gulden > util > text > TextTable


1 /*
2  * Project: Gulden Utilies
3  * Class: de.gulden.util.text.TextTable
4  * Version: snapshot-beautyj-1.1
5  *
6  * Date: 2004-09-29
7  *
8  * This is a snapshot version of the Gulden Utilities,
9  * it is not released as a seperate version.
10  *
11  * Note: Contains auto-generated Javadoc comments created by BeautyJ.
12  *
13  * This is licensed under the GNU Lesser General Public License (LGPL)
14  * and comes with NO WARRANTY.
15  *
16  * Author: Jens Gulden
17  * Email: amoda@jensgulden.de
18  */

19
20 package de.gulden.util.text;
21
22 import de.gulden.util.Toolbox;
23 import java.util.*;
24 import java.util.Collection JavaDoc;
25
26 /**
27  * Class TextTable.
28  *
29  * @author Jens Gulden
30  * @version snapshot-beautyj-1.1
31  */

32 public class TextTable {
33
34     // ------------------------------------------------------------------------
35
// --- fields ---
36
// ------------------------------------------------------------------------
37

38     /**
39      * The column count.
40      */

41     protected int columnCount;
42
43     /**
44      * The rows.
45      */

46     protected Collection JavaDoc rows;
47
48     /**
49      * The column weight array.
50      */

51     protected double[] columnWeight;
52
53     /**
54      * The border.
55      */

56     protected boolean border;
57
58     /**
59      * The borderchar.
60      */

61     protected char borderchar;
62
63     /**
64      * The max width.
65      */

66     protected int maxWidth;
67
68
69     // ------------------------------------------------------------------------
70
// --- constructors ---
71
// ------------------------------------------------------------------------
72

73     /**
74      * Creates a new instance of TextTable.
75      */

76     public TextTable(int columnCount, int width) {
77         this(columnCount,width,initArray(columnCount),'+');
78     }
79
80     /**
81      * Creates a new instance of TextTable.
82      */

83     public TextTable(int columnCount, int maxWidth, double[] columnWeights, char borderchar) {
84         this.columnCount=columnCount;
85         this.maxWidth=maxWidth;
86         this.columnWeight=columnWeights;
87         this.borderchar=borderchar;
88         rows=new ArrayList();
89     }
90
91
92     // ------------------------------------------------------------------------
93
// --- methods ---
94
// ------------------------------------------------------------------------
95

96     /**
97      * Adds a row.
98      */

99     public void addRow(String JavaDoc[] row) {
100         rows.add(row);
101     }
102
103     public String JavaDoc toString() {
104         // get all individual words
105
String JavaDoc[][][] tableWords=new String JavaDoc[rows.size()][columnCount][];
106         int row=0;
107         for (Iterator it=rows.iterator();it.hasNext();) {
108             String JavaDoc[] cols=(String JavaDoc[])it.next();
109             for (int col=0;col<columnCount;col++) {
110                 String JavaDoc text=cols[col];
111                 String JavaDoc[] words=splitWords(text);
112                 tableWords[row][col]=words;
113             }
114             row++;
115         }
116         // get widths
117
int[] width=new int[columnCount];
118         int minW=0;
119         for (int col=0;col<columnCount;col++) {
120             width[col]=minimumWidth(tableWords,col);
121             minW+=width[col];
122         }
123         minW+=(columnCount+1); // one space between each col
124
// can't help if minW>maxWidth, but if minW<maxWidth..:
125
int totalWidth;
126         if (minW<maxWidth) {
127             int rest=maxWidth-minW;
128             normalizeWeights();
129             totalWidth=0;
130             for (int i=0;i<columnCount;i++) {
131                 width[i]+=Math.round(((double)rest)*columnWeight[i]);
132                 totalWidth+=width[i];
133             }
134             totalWidth+=(columnCount+1);
135         } else {
136             totalWidth=minW;
137         }
138
139         // width[] now ok, create text boxes
140
String JavaDoc[][][] text=new String JavaDoc[rows.size()][columnCount][];
141         row=0;
142         for (Iterator it=rows.iterator();it.hasNext();) {
143             String JavaDoc[] r=(String JavaDoc[])it.next();
144             for (int col=0;col<columnCount;col++) {
145                 String JavaDoc s=r[col];
146                 text[row][col]=textBox(tableWords[row][col],width[col]);
147             }
148             row++;
149         }
150         // output
151
StringBuffer JavaDoc out=new StringBuffer JavaDoc();
152         for (row=0;row<text.length;row++) {
153             out.append(Toolbox.repeat(borderchar,totalWidth)+Toolbox.NL); // horizontal border
154
int maxHeight=0;
155             for (int col=0;col<columnCount;col++) {
156                 if (text[row][col].length>maxHeight) {
157                     maxHeight=text[row][col].length;
158                 }
159             }
160             for (int i=0;i<maxHeight;i++) {
161                 out.append(borderchar); // first vertical border
162
for (int col=0;col<columnCount;col++) {
163                     String JavaDoc t;
164                     if (i<text[row][col].length) {
165                         t=text[row][col][i];
166                     } else {
167                         t=Toolbox.repeat(" ",width[col]);
168                     }
169                     out.append(t+borderchar); // incl. vertical border
170
}
171                 out.append(Toolbox.NL);
172             }
173         }
174         out.append(Toolbox.repeat(borderchar,totalWidth)+Toolbox.NL); // last horizontal border
175
return out.toString();
176     }
177
178     private void normalizeWeights() {
179         double sum=0.0;
180         for (int i=0;i<columnCount;i++) {
181             sum+=columnWeight[i];
182         }
183         if (sum!=0.0) {
184             for (int i=0;i<columnCount;i++) {
185                 columnWeight[i]/=sum;
186             }
187         }
188         // else special case: all weights 0 (means: keep table on minimum width possible)
189
}
190
191
192     // ------------------------------------------------------------------------
193
// --- static methods ---
194
// ------------------------------------------------------------------------
195

196     /**
197      * Inits the array.
198      */

199     private static double[] initArray(int size) {
200         double[] d=new double[size];
201         for (int i=0;i<size;i++) {
202             d[i]=1.0;
203         }
204         return d;
205     }
206
207     private static int minimumWidth(String JavaDoc[][][] words, int column) {
208         int min=0;
209         for (int row=0;row<words.length;row++) {
210             String JavaDoc[] w=words[row][column];
211             for (int i=0;i<w.length;i++) {
212                 String JavaDoc s=w[i];
213                 if (s.length()>min) {
214                     min=s.length();
215                 }
216             }
217         }
218         return min;
219     }
220
221     private static String JavaDoc[] splitWords(String JavaDoc text) {
222         // returns line breaks as single words
223
Collection JavaDoc words=new ArrayList();
224                    StringTokenizer st=new StringTokenizer(text," \n", true);
225                    while (st.hasMoreTokens()) {
226                        String JavaDoc tok=st.nextToken();
227                        if (!tok.equals(" ")) {
228                            words.add(tok);
229                        }
230                    }
231                    String JavaDoc[] r=new String JavaDoc[words.size()];
232                    return (String JavaDoc[])words.toArray(r);
233     }
234
235     private static String JavaDoc[] textBox(String JavaDoc[] words, int width) {
236         Collection JavaDoc c=new ArrayList();
237         String JavaDoc line="";
238         int i=0;
239         boolean newline = false;
240         while (i<words.length) {
241             String JavaDoc word=words[i];
242             if (word.equals("\n")) {
243                 newline = true;
244                 i++;
245             } else {
246                 // truncate if too long so that it would fit into a yet blank line
247
if (word.length()>width) {
248                     word=word.substring(0,width);
249                 }
250                 boolean addSpace=(!line.equals(""))&&(!line.endsWith("-"));
251                 if (addSpace) {
252                     word=" "+word;
253                 }
254                 if ((line.length()+word.length())<=width) {
255                     line+=word;
256                     i++;
257                 } else {
258                     newline = true;
259                 }
260             }
261             if (newline) {
262                 line=Toolbox.padRight(line," ",width);
263                 c.add(line); // add code here to support center-aligned cells etc.
264
line="";
265                 newline = false;
266             }
267         }
268         if (!line.equals("")) {
269             line=Toolbox.padRight(line," ",width);
270             c.add(line);
271         }
272         String JavaDoc[] s=new String JavaDoc[c.size()];
273         return (String JavaDoc[])c.toArray(s);
274     }
275
276 } // end TextTable
277
Popular Tags