How to automatically scroll through JTextArea after adding?

I created a JFrame with JTextArea. I would like to automatically scroll the text area after each addition. How can I do it?

I tried log.setCaretPosition(log.getDocument().getLength()); but nothing has changed.

 package scrollit; import java.awt.*; import javax.swing.*; import static javax.swing.JFrame.EXIT_ON_CLOSE; public class ScrollIt extends JFrame { public static void main(String[] args) { ScrollIt sc = new ScrollIt(); } public ScrollIt() { super(); JTextArea log = new JTextArea(); log.setPreferredSize(new Dimension(50,50)); setDefaultCloseOperation(EXIT_ON_CLOSE); add(log); pack(); setVisible(true); log.append("a\n"); log.append("b\n"); log.append("c\n"); log.append("d\n"); log.append("e\n"); log.append("f\n"); } } 
+6
source share
2 answers

There are two ways (but JTextArea must be placed in JScrollPane )

a) install Caret (the right way)

eg.

  DefaultCaret caret = (DefaultCaret) log.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); 

b) moving from JScrollBar (from JScrollPane ) to its maximum value

+17
source

Mine is a bit simpler and more efficient. We set the caret to the length of the text to put it at the end like this.

 public void appendText(String str){ txtArea.append(str + "\n"); scrollDown(); } public void scrollDown(){ txtArea.setCaretPosition(txtArea.getText().length()); } 
0
source

All Articles