码迷,mamicode.com
首页 > 编程语言 > 详细

Java知识积累1-StringAlign实现文字居中左右对齐

时间:2015-04-25 22:39:15      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

import java.text.*;
public class StringAlign extends Format{
public static final int JUST_LEFT=‘l‘; //左对齐常量
public static final int JUST_RIGHT=‘r‘; //右对齐常量
public static final int JUST_CENTER=‘c‘; //居中常量
private int just; //当前的对其
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("必须是正数!");
}
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(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);
//调整化整误差
pad(where,maxChars-(where.length()-startPos));
break;

}
return where;
}
protected final void pad(StringBuffer to,int howMany){
for(int i=0;i<howMany;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;
}

}

Java知识积累1-StringAlign实现文字居中左右对齐

标签:

原文地址:http://www.cnblogs.com/ljbky/p/4456752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!