Swing/CaretPosition のバックアップの現在との差分(No.9)
TITLE:JTextPaneで最終行に移動
JTextPaneで最終行に移動
編集者:Terai Atsuhiro~
作成日:2005-08-01
更新日:2021-04-22 (木) 21:54:03
概要
CaretPosition
を指定してJTextPane
の最終行に移動します。
Screenshot
Advertisement
概要
CaretPositionを指定してJTextPaneの最終行に移動します。#screenshot
サンプルコード
#spanend
Document doc = jtp.getDocument();
try{
doc.insertString(doc.getLength(), str+"\n", null);
jtp.setCaretPosition(doc.getLength());
}catch(BadLocationException e) {}
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#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
- &jnlp;
- &jar;
- &zip;
解説
上記のサンプルでは、Documentに文字列と改行*1を追加した後、そのDocumentの一番最後にJTextComponent#setCaretPosition(int)メソッドでキャレットを移動しています。解説
上記のサンプルでは、Document
に文字列と改行を追加した後、そのDocument
の一番最後にJTextComponent#setCaretPosition(int)
メソッドでCaret
を移動しています。
Documentの最後ではなく、現在のキャレットの位置から、その行番号を取得したい場合は、以下のようにします。
-
JTextComponent
内での改行は常に\n
のためSystem.getProperties("line.separator")
で取得したり\r\n
を考慮する必要はない - 現在の
Caret
位置の行番号を取得する場合のサンプルpublic static int getLineAtCaret(JTextComponent component) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); return root.getElementIndex(caretPosition)+1; } #spanadd public static int getLineAtCaret(JTextComponent component) { #spanend int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); return root.getElementIndex(caretPosition) + 1; #spanadd } #spanend
参考リンク
参考リンク
- JScrollPaneのオートスクロール
- Swing - Line Number in JTextPane
- How to set AUTO-SCROLLING of JTEXTAREA in Java GUI? - Stack Overflow