Swing/FirstCharToUpperCase のバックアップ(No.20)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/FirstCharToUpperCase へ行く。
- 1 (2010-03-01 (月) 12:38:41)
- 2 (2010-03-04 (木) 19:28:00)
- 3 (2010-03-08 (月) 14:53:09)
- 4 (2011-06-26 (日) 01:17:01)
- 5 (2011-06-27 (月) 19:21:21)
- 6 (2012-10-19 (金) 20:10:12)
- 7 (2013-01-02 (水) 14:26:43)
- 8 (2013-05-26 (日) 04:54:59)
- 9 (2015-01-08 (木) 14:01:57)
- 10 (2015-11-27 (金) 17:44:03)
- 11 (2017-01-06 (金) 19:16:42)
- 12 (2017-04-04 (火) 15:11:18)
- 13 (2018-03-18 (日) 10:03:27)
- 14 (2020-03-20 (金) 19:46:42)
- 15 (2021-09-26 (日) 09:47:18)
- 16 (2023-05-08 (月) 12:23:39)
- 17 (2025-01-03 (金) 08:57:02)
- 18 (2025-01-03 (金) 09:01:23)
- 19 (2025-01-03 (金) 09:02:38)
- 20 (2025-01-03 (金) 09:03:21)
- 21 (2025-01-03 (金) 09:04:02)
- category: swing
folder: FirstCharToUpperCase
title: DocumentFilterで先頭文字を大文字に変換する
tags: [JTextField, DocumentFilter]
author: aterai
pubdate: 2010-03-01T12:38:41+09:00
description: DocumentFilterを使って、文字列の先頭が常に大文字になるように設定します。
image:
Summary
DocumentFilter
を使って、文字列の先頭が常に大文字になるように設定します。
Screenshot

Advertisement
Source Code Examples
class FirstCharToUpperCaseDocumentFilter extends DocumentFilter {
private final JTextComponent textField;
protected FirstCharToUpperCaseDocumentFilter(JTextComponent textField) {
super();
this.textField = textField;
}
@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 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);
}
}
View in GitHub: Java, KotlinExplanation
上記のサンプルでは、JTextField
に入力された文字列の先頭一文字が、常に大文字になるように変換するDocumentFilter
を設定しています。
JFormattedTextField
+MaskFormatter
を使用すると指定した文字列長に足りない場合などでアンドゥが実行されるfield1 = new JFormattedTextField(new MaskFormatter("ULLLLLLLLLL"));