Import java.text.*;
public class Stringalign extends format{
public static final int just_left= ' l '; Left-to-Chi Chang volume
public static final int just_right= ' R '; Right to Chi Chang amount
public static final int just_center= ' C '; Center constant
private int just; The current pair of its
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 contents of the maximum line width are 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);
Adjustment of the rounding error
Pad (where,maxchars-(where.length ()-startpos));
Break
}
return where;
}
protected final void pad (StringBuffer to,int howmany) {
for (int i=0;iTo.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;
}
}
Java Knowledge Accumulation 1-stringalign Implement text center right-to-left alignment