Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto scroll down JTextArea after append?

I've created a JFrame, with a JTextArea. I would like to scroll down the textarea automatically, after each append. How should I manage it?

I've tried log.setCaretPosition(log.getDocument().getLength());, but nothing 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");
    }
}
like image 480
Iter Ator Avatar asked Apr 29 '14 13:04

Iter Ator


2 Answers

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

a) set Caret (correct of ways)

e.g.

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

b) moving with JScrollBar (from JScrollPane) to its max value

like image 107
mKorbel Avatar answered Oct 05 '22 20:10

mKorbel


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

public void appendText(String str){
    txtArea.append(str + "\n");
    scrollDown();
}

public void scrollDown(){
    txtArea.setCaretPosition(txtArea.getText().length());
}
like image 32
user3498796 Avatar answered Oct 05 '22 19:10

user3498796