Swing/SelectAllWhileKeepingVisibleRect のバックアップ(No.5)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/SelectAllWhileKeepingVisibleRect へ行く。
- 1 (2025-03-10 (月) 00:56:20)
- 2 (2025-03-10 (月) 05:10:30)
- 3 (2025-03-11 (火) 21:25:49)
- 4 (2025-06-19 (木) 12:41:37)
- 5 (2025-06-19 (木) 12:43:47)
- category: swing folder: SelectAllWhileKeepingVisibleRect title: JTextAreaの全選択で表示領域を維持する tags: [JTextArea, JScrollPane, JTextComponent, ActionMap, InputMap, Caret] author: aterai pubdate: 2025-03-10T00:52:54+09:00 description: JTextAreaの複数行テキストをすべて選択したとき、末尾のキャレット位置までスクロールするのではなく、全選択前の表示領域を維持する全選択アクションを作成します。 image: https://drive.google.com/uc?id=1vbNvUI8-oiwqmf9KVlVeoZCBpsmvZHMb
Summary
JTextAreaの複数行テキストをすべて選択したとき、末尾のキャレット位置までスクロールするのではなく、全選択前の表示領域を維持する全選択アクションを作成します。
Screenshot

Advertisement
Source Code Examples
@Override public void selectAll() {
Rectangle r = getVisibleRect();
Document doc = getDocument();
if (doc != null) {
if (isEmacs) {
setCaretPosition(doc.getLength());
moveCaretPosition(0);
} else { // Visual Studio Code
setCaretPosition(0);
moveCaretPosition(doc.getLength());
}
}
EventQueue.invokeLater(() -> scrollRectToVisible(r));
}
View in GitHub: Java, KotlinDescription
Default- デフォルトの
JTextComponentのselect-allアクションは全選択でCaretは全テキスト末尾に移動し、表示領域もその末尾までスクロールする Apache NetBeansやメモ帳(notepad.exe)の動作と同じ
- デフォルトの
Override selectAllJTextComponent#selectAll()、またはDefaultEditorKit#SelectAllActionをオーバーライドし、全選択前の表示領域をJTextComponent#getVisibleRect()で保存、全選択後にその領域をJTextComponent#scrollRectToVisible(...)で復元JTextComponent#selectAll()メソッドとCtrl+Aで実行されるDefaultEditorKit#SelectAllActionはどちらも同じようにsetCaretPosition(0); moveCaretPosition(doc.getLength());を実行しているが、別々に実装されているので注意が必要Visual Studio Codeなどと同様で全選択後のCaretは全テキスト末尾に移動するが、表示領域は移動しない- 選択状態で↑、←キー入力すると選択していた文字列の先頭に
Caret移動するようInputMap、ActionMapを調節
move Caret topOverride selectAllと同様の表示領域を維持する処理に加えて、全選択後のCaret位置を全テキスト先頭に変更GNU Emacsやxyzzyなどの動作と同じになる- 選択状態で↓、→キー入力すると選択していた文字列の末尾に
Caret移動するようInputMap、ActionMapを調節
IntelliJ IDEAのように全選択でCaret位置を移動しないようにする方法をJTextComponentで再現するのは無理そう?- intellij-community/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/EditorUtil.java at master · JetBrains/intellij-community
- intellij-community/platform/editor-ui-api/src/com/intellij/openapi/editor/Caret.java at master · JetBrains/intellij-community
- intellij-community/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretImpl.java at master · JetBrains/intellij-community
- intellij-community/platform/editor-ui-api/src/com/intellij/openapi/editor/Editor.java at master · JetBrains/intellij-community
- intellij-community/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java at master · JetBrains/intellij-community
Reference
- JTextComponent#selectAll() (Java Platform SE 8)
- DefaultEditorKit#selectAllAction (Java Platform SE 8)