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

#contents

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

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

#screenshot

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

**解説 [#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;
 }
public static int getLineAtCaret(JTextComponent component) {
  int caretPosition = component.getCaretPosition();
  Element root = component.getDocument().getDefaultRootElement();
  return root.getElementIndex(caretPosition)+1;
}
}}

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

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