Java knowledge accumulation 1-StringAlign achieves align between left and right text, java1-stringalign
Import java. text .*;
Public class StringAlign extends Format {
Public static final int JUST_LEFT = 'l'; // left-aligned constant
Public static final int JUST_RIGHT = 'R'; // right-aligned constant
Public static final int JUST_CENTER = 'C'; // center constant
Private int just; // The current
Private int maxChars;
Public StringAlign (int maxChars, int just ){
Switch (just ){
Case JUST_CENTER:
Case JUST_LEFT:
Case JUST_RIGHT:
This. just = just;
Break;
Default:
Throw new IllegalArgumentException ("invalid justification arg .");
}
If (maxChars <0 ){
Throw new IllegalArgumentException ("must be a positive number! ");
}
This. maxChars = maxChars;
}
Public StringBuffer format (Object obj, StringBuffer where, FieldPosition ignore ){
String s = (String) obj;
String wanted = s. substring (0, Math. min (s. length (), maxChars ));
// If there is no space for alignment, the content of the largest row width is returned.
If (wanted. length ()> maxChars ){
Where. append (wanted );
}
Else switch (just ){
Case JUST_RIGHT:
Pad (where, maxChars-wanted.length ());
Where. append (wanted );
Break;
Case JUST_LEFT:
Where. append (wanted );
Pad (where, maxChars-wanted.length ());
Break;
Case JUST_CENTER:
Int startPos = where. length ();
Pad (where, (maxChars-wanted.length ()/2 );
Where. append (wanted );
Pad (where, (maxChars-wanted.length ()/2 );
// Adjusted the integer Error
Pad (where, maxChars-(where. length ()-startPos ));
Break;
}
Return where;
}
Protected final void pad (StringBuffer to, int howpad ){
For (int I = 0; I To. append ('');
}
}
String format (String s ){
Return format (s, new StringBuffer (), null). toString ();
}
@ Override
Public Object parseObject (String source, ParsePosition pos ){
// TODO Auto-generated method stub
Return source;
}
}