JTextPaneで最終行に移動

編集者:Terai Atsuhiro~

作成日:2005-08-01
更新日:2021-04-22 (木) 21:54:03
  • 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: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTId9wo-yI/AAAAAAAAAS0/GZbZiJfMOwI/s800/CaretPosition.png

概要

CaretPositionを指定してJTextPaneの最終行に移動します。

概要

CaretPositionを指定してJTextPaneの最終行に移動します。

サンプルコード

#spanend
#spanadd
Document doc = jtp.getDocument();
#spanend
#spanadd
try {
#spanend
  doc.insertString(doc.getLength(), text + "\n", null);
  jtp.setCaretPosition(doc.getLength());
#spanadd
} catch (BadLocationException ex) {
#spanend
  ex.printStackTrace();
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin
http://terai.xrea.jp/swing/caretposition/screenshot.png

解説

上記のサンプルでは、Documentに文字列と改行を追加した後、そのDocumentの一番最後にJTextComponent#setCaretPosition(int)メソッドでCaretを移動しています。

サンプルコード

Document doc = jtp.getDocument();
try{
  doc.insertString(doc.getLength(), str+"\n", null);
  jtp.setCaretPosition(doc.getLength());
}catch(BadLocationException e) {}
  • JTextComponent内での改行は常に\nのためSystem.getProperties("line.separator")で取得したり\r\nを考慮する必要はない
  • 現在のCaret位置の行番号を取得する場合のサンプル
    #spanend
    #spanadd
    public static int getLineAtCaret(JTextComponent component) {
    #spanend
      int caretPosition = component.getCaretPosition();
      Element root = component.getDocument().getDefaultRootElement();
      return root.getElementIndex(caretPosition) + 1;
    #spanadd
    }
    #spanend
    #spanadd
    

参考リンク

解説

上記のサンプルでは、Documentに文字列と改行*1を追加した後、そのDocumentの一番最後にJTextComponent#setCaretPosition(int)メソッドでキャレットを移動しています。 Documentの最後ではなく、現在のキャレットの位置から、その行番号を取得したい場合は、以下のようにします。
public static int getLineAtCaret(JTextComponent component) {
  int caretPosition = component.getCaretPosition();
  Element root = component.getDocument().getDefaultRootElement();
  return root.getElementIndex(caretPosition)+1;
}

参考リンク

コメント

コメント