Swing/FirstCharToUpperCase のバックアップの現在との差分(No.1)
TITLE:DocumentFilterで先頭文字を大文字に変換する
Posted by terai at 2010-03-01
DocumentFilterで先頭文字を大文字に変換する
DocumentFilterを使って、文字列の先頭が常に大文字になるように設定します。- category: swing folder: FirstCharToUpperCase title: DocumentFilterで先頭文字を大文字に変換する tags: [JTextField, DocumentFilter] author: aterai pubdate: 2010-03-01T12:38:41+09:00 description: DocumentFilterを使って、文字列の先頭が常に大文字になるように設定します。 image:
概要
DocumentFilter
を使って、文字列の先頭が常に大文字になるように設定します。
- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
#screenshot
サンプルコード
#spanend
#spandel
class FirstCharToUpperCaseDocumentFilter extends {
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
class FirstCharToUpperCaseDocumentFilter extends DocumentFilter {
private final JTextComponent textArea;
public FirstCharToUpperCaseDocumentFilter(JTextComponent textArea) {
private final JTextComponent textField;
protected FirstCharToUpperCaseDocumentFilter(JTextComponent textField) {
super();
this.textArea = textArea;
this.textField = textField;
}
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs)
throws BadLocationException {
if(text==null) return;
replace(fb, offset, 0, text, attrs);
#spanadd
#spanend
@Override public void remove(
DocumentFilter.FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
if (offset == 0 && doc.getLength() - length > 0) {
fb.replace(length, 1,
doc.getText(length, 1).toUpperCase(Locale.ENGLISH), null);
textField.setCaretPosition(offset);
}
fb.remove(offset, length);
}
@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);
}
#spanadd
#spanend
@Override public void replace(
DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
String str = text;
if (offset == 0 && Objects.nonNull(text) && !text.isEmpty()) {
str = text.substring(0, 1).toUpperCase(Locale.ENGLISH) + text.substring(1);
}
fb.replace(offset, length, str, attrs);
}
}
解説
上記のサンプルでは、JTextFeild内の文字列の先頭一文字が、常に大文字になるように変換するDocumentFilterを作成しています。解説
上記のサンプルでは、JTextField
に入力された文字列の先頭一文字が、常に大文字になるように変換するDocumentFilter
を設定しています。
参考リンク
コメント
-
JFormattedTextField
+MaskFormatter
を使用すると指定した文字列長に足りない場合などでアンドゥが実行される#spanend #spanadd field1 = new JFormattedTextField(new MaskFormatter("ULLLLLLLLLL")); #spanend #spanadd