Swing/CaretPosition のバックアップの現在との差分(No.21)
- category: swing folder: CaretPosition title: JTextPaneで最終行に移動 tags: [JTextPane, JTextComponent, Caret, Document] author: aterai pubdate: 2005-08-01T02:22:59+09:00 description: CaretPositionを指定してJTextPaneの最終行に移動します。 image:
概要
CaretPosition
を指定してJTextPane
の最終行に移動します。
Screenshot
Advertisement
サンプルコード
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, Kotlin解説
上記のサンプルでは、Document
に文字列と改行を追加した後、そのDocument
の一番最後にJTextComponent#setCaretPosition(int)
メソッドでCaret
を移動しています。
-
JTextComponent
内での改行は常に\n
であり、System.getProperties("line.separator")
で取得したり、\r\n
を考慮する必要はない -
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; }
参考リンク
- JScrollPaneのオートスクロール
- Swing - Line Number in JTextPane
- How to set AUTO-SCROLLING of JTEXTAREA in Java GUI? - Stack Overflow