TITLE:DocumentFilterで先頭文字を大文字に変換する
#navi(../)
RIGHT:Posted by [[terai]] at 2010-03-01
*DocumentFilterで先頭文字を大文字に変換する [#kb40e964]
DocumentFilterを使って、文字列の先頭が常に大文字になるように設定します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#c5239278]
#code{{
class FirstCharToUpperCaseDocumentFilter extends  {
class FirstCharToUpperCaseDocumentFilter extends DocumentFilter {
  private final JTextComponent textArea;
  public FirstCharToUpperCaseDocumentFilter(JTextComponent textArea) {
    super();
    this.textArea = textArea;
  }
  @Override
  public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs)
        throws BadLocationException {
    if(text==null) return;
    replace(fb, offset, 0, text, attrs);
  }
  @Override
  public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
     Document doc = fb.getDocument();
     if(offset==0 && doc.getLength()-length>0) {
       fb.replace(0, length+1, doc.getText(length, 1).toUpperCase(), null);
       textArea.setCaretPosition(0);
     } else {
       fb.remove(offset, length);
     }
   }
  @Override
  public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
        throws BadLocationException {
     if(offset==0 && text!=null && text.length()>0) {
       text = text.substring(0,1).toUpperCase()+text.substring(1);
     }
     fb.replace(offset, length, text, attrs);
   }
}
}}

**解説 [#g58b7cc5]
上記のサンプルでは、JTextFeild内の文字列の先頭一文字が、常に大文字になるように変換するDocumentFilterを作成しています。

**参考リンク [#tc929037]
**コメント [#yc833a25]
#comment