• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTextPaneで最終行に移動
#navi(../)
#tags(JTextPane, JTextComponent, Caret, Document)
RIGHT:Posted by &author(aterai); at 2005-08-01
* JTextPaneで最終行に移動 [#rf478a7f]
``CaretPosition``を指定して``JTextPane``の最終行に移動します。
---
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
---
* 概要 [#summary]
`CaretPosition`を指定して`JTextPane`の最終行に移動します。

- &jnlp;
- &jar;
- &zip;
#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTId9wo-yI/AAAAAAAAAS0/GZbZiJfMOwI/s800/CaretPosition.png)

#ref(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTId9wo-yI/AAAAAAAAAS0/GZbZiJfMOwI/s800/CaretPosition.png)

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

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

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

- `JTextComponent`内での改行は常に`\n`のため`System.getProperties("line.separator")`で取得したり`\r\n`を考慮する必要はない
- 現在の`Caret`位置の行番号を取得する場合のサンプル
#code{{
public static int getLineAtCaret(JTextComponent component) {
  int caretPosition = component.getCaretPosition();
  Element root = component.getDocument().getDefaultRootElement();
  return root.getElementIndex(caretPosition)+1;
  return root.getElementIndex(caretPosition) + 1;
}
}}

** 参考リンク [#tea24622]
* 参考リンク [#reference]
- [[JScrollPaneのオートスクロール>Swing/AutoScroll]]
- [https://forums.oracle.com/message/5882821 Line Number in JTextPane | Oracle Forums]
- [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]
- [https://community.oracle.com/thread/1393939 Swing - Line Number in JTextPane]
- [https://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]
#comment
#comment