Swing/LastLineEditableTextArea のバックアップ(No.1)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/LastLineEditableTextArea へ行く。
- 1 (2013-01-09 (水) 12:35:02)
- 2 (2015-01-07 (水) 16:19:39)
- 3 (2016-05-25 (水) 13:51:45)
- 4 (2017-08-10 (木) 14:48:51)
- 5 (2018-08-21 (火) 14:21:39)
- 6 (2020-08-18 (火) 05:05:14)
- 7 (2022-01-15 (土) 15:17:01)
- 8 (2025-01-03 (金) 08:57:02)
- 9 (2025-01-03 (金) 09:01:23)
- 10 (2025-01-03 (金) 09:02:38)
- 11 (2025-01-03 (金) 09:03:21)
- 12 (2025-01-03 (金) 09:04:02)
- 13 (2025-06-19 (木) 12:41:37)
- 14 (2025-06-19 (木) 12:43:47)
TITLE:JTextAreaの最終行だけ編集可能になるよう設定する
Posted by aterai at 2012-12-24
JTextAreaの最終行だけ編集可能になるよう設定する
`DocumentFilterを使用して最終行のみ編集可能なJTextArea`を作成します。
- &jnlp;
- &jar;
- &zip;
サンプルコード
class NonEditableLineDocumentFilter extends DocumentFilter {
public static final String PROMPT = "> ";
@Override public void insertString(
DocumentFilter.FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
if(string == null) {
return;
}else{
replace(fb, offset, 0, string, attr);
}
}
@Override public void remove(
DocumentFilter.FilterBypass fb,
int offset, int length) throws BadLocationException {
replace(fb, offset, length, "", null);
}
@Override public void replace(
DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
Element root = doc.getDefaultRootElement();
int count = root.getElementCount();
int index = root.getElementIndex(offset);
Element cur = root.getElement(index);
int promptPosition = cur.getStartOffset()+PROMPT.length();
if(index==count-1 && offset-promptPosition>=0) {
if(text.equals("\n")) {
String line = doc.getText(promptPosition, offset-promptPosition);
String[] args = line.split(" ");
String cmd = args[0];
if(cmd.isEmpty()) {
text = "";
}else{
text = String.format("\n%s: command not found", cmd);
}
text += "\n"+PROMPT;
}
fb.replace(offset, length, text, attrs);
}
}
}
View in GitHub: Java, Kotlin解説
- `
DocumentFilter#replace(...)`をオーバーライド - `
Document#getDefaultRootElement()でルートエレメントを取得し、Element#getElementCount()`で全体の行数を取得 - `
offset(文字挿入位置)からElement#getElementIndex(offset)で、挿入位置の行番号と、Element`を取得 - 上記の「挿入位置の行番号」と「全体の行数-1」が等しい場合だけ、`
DocumentFilter.FilterBypass#replace(...)`を実行(編集可能)する- 上記のサンプルでは、コマンドプロンプト風に、最終行の行頭にあるプロンプトは編集不可で、改行の入力ごとに最終行の文字列を評価してメッセージを追加表示している
