1 16 package org.jmanage.cmdui.util; 17 18 import org.jmanage.util.StringUtils; 19 20 import java.util.List ; 21 import java.util.LinkedList ; 22 import java.util.Iterator ; 23 24 30 public class Table { 31 32 private static final int COLUMN_SPACING = 5; 33 34 private Object [] header; 35 private final int columns; 36 private final List rows; 37 38 private final int[] columnSize; 39 40 public Table(int columns){ 41 this.columns = columns; 42 this.rows = new LinkedList (); 43 this.columnSize = new int[columns]; 44 } 45 46 public void add(Object obj1, Object obj2){ 47 add(new Object []{obj1, obj2}); 48 } 49 50 public void add(Object obj1, Object obj2, Object obj3){ 51 add(new Object []{obj1, obj2, obj3}); 52 } 53 54 public void add(Object obj1, Object obj2, Object obj3, Object obj4){ 55 add(new Object []{obj1, obj2, obj3, obj4}); 56 } 57 58 public void add(Object obj1, Object obj2, Object obj3, Object obj4, Object obj5){ 59 add(new Object []{obj1, obj2, obj3, obj4, obj5}); 60 } 61 62 public void add(Object [] objects){ 63 assert columns == objects.length; 64 rows.add(objects); 65 setColumnSize(objects); 66 } 67 68 public void setHeader(Object [] header) { 69 this.header = header; 70 setColumnSize(header); 71 } 72 73 private void setColumnSize(Object [] objects){ 74 for(int i=0; i<objects.length; i++){ 75 if(objects[i].toString().length() > columnSize[i]) 76 columnSize[i] = objects[i].toString().length(); 77 } 78 } 79 80 public void print(){ 81 Out.println(); 82 if(header != null){ 83 printRow(header); 84 printUnderline(header); 85 } 86 for(Iterator it=rows.iterator(); it.hasNext();){ 87 Object [] cols = (Object [])it.next(); 88 printRow(cols); 89 } 90 } 91 92 private void printRow(Object [] cols){ 93 for(int i=0; i < columns; i++){ 94 String columnValue = StringUtils.padRight(cols[i].toString(), 95 columnSize[i] + COLUMN_SPACING); 96 Out.print(columnValue); 97 } 98 Out.println(); 99 } 100 101 private void printUnderline(Object [] cols){ 102 for(int i=0; i < columns; i++){ 103 String underline = 104 StringUtils.getCharSeries('-', cols[i].toString().length()); 105 underline = StringUtils.padRight(underline, 106 columnSize[i] + COLUMN_SPACING); 107 Out.print(underline); 108 } 109 Out.println(); 110 } 111 } 112 | Popular Tags |