1 package gnu.text; 2 import java.text.*; 3 import java.text.FieldPosition ; 4 import java.io.Writer ; 5 6 7 8 public class PadFormat extends ReportFormat 9 { 10 11 int minWidth; 12 char padChar; 13 15 int where; 16 17 Format fmt; 18 19 public PadFormat(Format fmt, int minWidth, char padChar, int where) 20 { 21 this.fmt = fmt; 22 this.minWidth = minWidth; 23 this.padChar = padChar; 24 this.where = where; 25 } 26 27 public PadFormat(Format fmt, int minWidth) 28 { 29 this(fmt, minWidth, ' ', 100); 30 } 31 32 public int format(Object [] args, int start, 33 Writer dst, FieldPosition fpos) 34 throws java.io.IOException 35 { 36 return format(fmt, args, start, dst, padChar, minWidth, 1, 0, where, fpos); 37 } 38 39 public static int padNeeded(int actualWidth, 40 int minWidth, int colInc, int minPad) 41 { 42 int total = actualWidth + minPad; 43 if (colInc <= 1) 44 colInc = minWidth - total; 45 while (total < minWidth) 46 total += colInc; 47 return total - actualWidth; 48 } 49 50 public static int format(Format fmt, Object [] args, int start, Writer dst, 51 char padChar, int minWidth, int colInc, int minPad, 52 int where, FieldPosition fpos) 53 throws java.io.IOException 54 { 55 67 68 StringBuffer tbuf = new StringBuffer (200); 69 if (fmt instanceof ReportFormat) 70 start = ((ReportFormat)fmt).format(args, start, tbuf, fpos); 71 else if (fmt instanceof MessageFormat) 72 { 73 fmt.format(args, tbuf, fpos); 75 start = args.length; 76 } 77 else 78 { 79 fmt.format(args[start], tbuf, fpos); 80 start++; 81 } 82 int len = tbuf.length(); 83 int pad = padNeeded(len, minWidth, colInc, minPad); 84 int prefix = 0; 85 String text = tbuf.toString(); 86 if (pad > 0) 87 { 88 if (where == -1) 89 { 90 if (len > 0) 91 { 92 char ch = text.charAt(0); 93 if (ch == '-' || ch == '+') 94 { 95 prefix++; 96 dst.write(ch); 97 } 98 if (len - prefix > 2 && text.charAt(prefix) == '0') 99 { 100 dst.write('0'); 101 ch = text.charAt(++prefix); 102 if (ch == 'x' || ch == 'X') 103 { 104 prefix++; 105 dst.write(ch); 106 } 107 } 108 if (prefix > 0) 109 text = text.substring(prefix); 110 } 111 where = 0; 112 } 113 int padAfter = (pad * where) / 100; 114 int padBefore = pad - padAfter; 115 123 while (--padBefore >= 0) 124 dst.write(padChar); 125 dst.write(text); 126 while (--padAfter >= 0) 127 dst.write(padChar); 128 } 129 else 130 { 131 dst.write(text); 132 } 133 return start; 134 } 135 } 136 | Popular Tags |