• 追加された行はこの色です。
  • 削除された行はこの色です。
#navi(../)
*JTextPaneで最終行に移動 [#rf478a7f]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-08-01~
更新日:&lastmod;

#contents

**概要 [#zab9af94]
CaretPositionを指定してJTextPaneの最終行に移動します。

http://terai.xrea.jp/swing/caretposition/screenshot.png
#screenshot

**サンプルコード [#i47b5978]
 Document doc = jtp.getDocument();
 try{
   doc.insertString(doc.getLength(), str+"\n", null);
   jtp.setCaretPosition(doc.getLength());
 }catch(BadLocationException e) {}

-[[サンプルを起動>http://terai.xrea.jp/swing/caretposition/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/caretposition/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/caretposition/src.zip]]
-&jnlp;
-&jar;
-&zip;

**解説 [#mee5ef8f]
上記のサンプルでは、Documentに文字列と改行((JTextPaneでは改行は"\n"であり、System.getProperties("line.separator")としたり、"\r\n"にする必要はない))を追加した後、その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;
 }

**参考リンク [#tea24622]
-[[JScrollPaneのオートスクロール>http://terai.xrea.jp/Swing/AutoScroll.html]]
-[[Java Forums - Line Number in JTextPane>http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613385]]

**コメント [#f7f203e1]
#comment