zoukankan      html  css  js  c++  java
  • Java知识积累1-StringAlign实现文字居中左右对齐

    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;
    }

    }

  • 相关阅读:
    C++小知识点
    C++类的const成员函数、默认的构造函数、复制形参调用函数
    原码、反码、补码,计算机中负数的表示
    linux学习笔记(一)
    涉及string、char *、char[ ]、逗号表达式 的代码
    软件皮肤 IrisSkin
    DataGridView 闪烁
    C# String StringBuider 解惑
    JTA事务总结
    世界真的存在吗
  • 原文地址:https://www.cnblogs.com/ljbky/p/4456752.html
Copyright © 2011-2022 走看看