---
category: swing
folder: NonEditableLine
title: JTextAreaの一部を編集不可にする
tags: [JTextArea, DocumentFilter, Highlighter]
author: aterai
pubdate: 2010-02-22T14:50:22+09:00
description: JTextAreaの一部の行を編集不可になるよう設定します。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTQW4ZQhAI/AAAAAAAAAfc/JkImmzMvG6I/s800/NonEditableLine.png
---
* Summary [#summary]
`JTextArea`の一部の行を編集不可になるよう設定します。
#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTQW4ZQhAI/AAAAAAAAAfc/JkImmzMvG6I/s800/NonEditableLine.png)
* Source Code Examples [#sourcecode]
#code(link){{
class NonEditableLineDocumentFilter extends DocumentFilter {
@Override public void insertString(
FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
if (Objects.nonNull(string)) {
replace(fb, offset, 0, string, attr);
}
}
@Override public void remove(
FilterBypass fb, int offset, int length)
throws BadLocationException {
replace(fb, offset, length, "", null);
}
@Override public void replace(
FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
Document doc = fb.getDocument();
if (doc.getDefaultRootElement().getElementIndex(offset) < 2) {
return;
}
fb.replace(offset, length, text, attrs);
}
}
}}
* Description [#explanation]
* Description [#description]
上記のサンプルでは、`DocumentFilter`を使って`JTextArea`の`1`行目と`2`行目で文字の追加、削除などの編集が不可になるよう設定しています。
#code{{
((AbstractDocument) textArea.getDocument()).setDocumentFilter(
new NonEditableLineDocumentFilter());
}}
- `1`行目と`2`行目の背景色は編集不可のための`DocumentFilter`とは無関係に`Highlighter`を使用して設定
#code{{
try {
Highlighter hilite = textArea.getHighlighter();
Document doc = textArea.getDocument();
Element root = doc.getDefaultRootElement();
for (int i = 0; i < 2; i++) {
Element elem = root.getElement(i);
hilite.addHighlight(elem.getStartOffset(),
elem.getEndOffset() - 1,
highlightPainter);
}
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}}
* Reference [#reference]
- [http://www.jroller.com/santhosh/date/20050622 Document Guard - Santhosh Kumar's Weblog]
- [[JTextAreaの最終行だけ編集可能になるよう設定する>Swing/LastLineEditableTextArea]]
* Comment [#comment]
#comment
#comment