• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTextPaneで最終行に移動
#navi(../)
RIGHT:Posted by [[terai]] at 2005-08-01
#tags()
RIGHT:Posted by &author(aterai); at 2005-08-01
*JTextPaneで最終行に移動 [#rf478a7f]
CaretPositionを指定してJTextPaneの最終行に移動します。

-&jnlp;
-&jar;
-&zip;

#screenshot
//#screenshot
#ref(http://lh4.ggpht.com/_9Z4BYR88imo/TQTId9wo-yI/AAAAAAAAAS0/GZbZiJfMOwI/s800/CaretPosition.png)

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

**解説 [#mee5ef8f]
上記のサンプルでは、Documentに文字列と改行((JTextPaneでは改行は"\n"であり、System.getProperties("line.separator")としたり、"\r\n"にする必要はない))を追加した後、そのDocumentの一番最後にJTextComponent#setCaretPosition(int)メソッドでキャレットを移動しています。

Documentの最後ではなく、現在のキャレットの位置から、その行番号を取得したい場合は、以下のようにします。

#code{{
public static int getLineAtCaret(JTextComponent component) {
  int caretPosition = component.getCaretPosition();
  Element root = component.getDocument().getDefaultRootElement();
  return root.getElementIndex(caretPosition)+1;
}
}}

**参考リンク [#tea24622]
-[[JScrollPaneのオートスクロール>Swing/AutoScroll]]
-[[Swing - Line Number in JTextPane>http://forums.sun.com/thread.jspa?threadID=613385]]
-[http://forums.sun.com/thread.jspa?threadID=613385 Swing - Line Number in JTextPane]
-[http://stackoverflow.com/questions/1627028/how-to-set-auto-scrolling-of-jtextarea-in-java-gui How to set AUTO-SCROLLING of JTEXTAREA in Java GUI? - Stack Overflow]

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