JTextAreaの全選択で表示領域を維持する
Total: 86
, Today: 1
, Yesterday: 1
Posted by aterai at
Last-modified:
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, KotlinExplanation
Default
- デフォルトの
JTextComponent
のselect-all
アクションは全選択でCaret
は全テキスト末尾に移動し、表示領域もその末尾までスクロールする Apache NetBeans
やメモ帳(notepad.exe
)の動作と同じ
- デフォルトの
Override selectAll
JTextComponent#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 top
Override 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)