Java Reference
In-Depth Information
public
public
StringAlign
(
int
int
maxChars
,
Justify just
) {
switch
switch
(
just
) {
case
case
LEFT:
case
case
CENTER:
case
case
RIGHT:
this
this
.
just
=
just
;
break
break
;
default
default
:
throw
throw new
new
IllegalArgumentException
(
"invalid justification arg."
);
}
iif
(
maxChars
<
0
) {
throw
throw new
new
IllegalArgumentException
(
"maxChars must be positive."
);
}
this
this
.
maxChars
=
maxChars
;
}
/** Format a String.
* @param input - the string to be aligned.
* @parm where - the StringBuffer to append it to.
* @param ignore - a FieldPosition (may be null, not used but
* specified by the general contract of Format).
*/
public
public
StringBuffer
format
(
Object input
,
StringBuffer where
,
FieldPosition ignore
) {
String s
=
input
.
toString
();
String wanted
=
s
.
substring
(
0
,
Math
.
min
(
s
.
length
(),
maxChars
));
// Get the spaces in the right place.
switch
switch
(
just
) {
case
case
RIGHT:
pad
(
where
,
maxChars
-
wanted
.
length
());
where
.
append
(
wanted
);
break
break
;
case
case
CENTER:
int
int
toAdd
=
maxChars
-
wanted
.
length
();
pad
(
where
,
toAdd
/
2
);
where
.
append
(
wanted
);
pad
(
where
,
toAdd
-
toAdd
/
2
);
break
break
;
case
case
LEFT:
where
.
append
(
wanted
);
pad
(
where
,
maxChars
-
wanted
.
length
());
break
break
;
}
return
return
where
;