JTextPaneで最終行に移動
Total: 16681, Today: 1, Yesterday: 1
Posted by aterai at
Last-modified:
Summary
CaretPositionを指定してJTextPaneの最終行に移動します。
Screenshot

Advertisement
Source Code Examples
Document doc = jtp.getDocument();
try {
doc.insertString(doc.getLength(), text + "\n", null);
jtp.setCaretPosition(doc.getLength());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
View in GitHub: Java, KotlinDescription
上記のサンプルでは、Documentに文字列と改行を追加した後、そのDocumentの一番最後にJTextComponent#setCaretPosition(int)メソッドでCaretを移動しています。
JTextComponent内での改行は常に\nのためSystem.getProperties("line.separator")で取得したり\r\nを考慮する必要はない- 現在の
Caret位置の行番号を取得する場合のサンプルpublic static int getLineAtCaret(JTextComponent component) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); return root.getElementIndex(caretPosition) + 1; }
Reference
- JScrollPaneのオートスクロール
- Swing - Line Number in JTextPane
- How to set AUTO-SCROLLING of JTEXTAREA in Java GUI? - Stack Overflow