Hacer AutoScroll en un JScrollPane de Java Swing

En este ejemplo se muestra como hacer un autoscroll de un JTextArea mientras este se va llenado. Para realizar esta operación creo la funcion addText() la cual realiza todo el proceso.

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class Principal extends JFrame {
    private static final long serialVersionUID = 1L;
    JTextArea texto = new JTextArea();
    JScrollPane scrollpnl = new JScrollPane();
    public Principal() {

        scrollpnl.getViewport().add(texto);
        getContentPane().add(scrollpnl);
        setSize(new Dimension(800, 600));
        setVisible(true);
        new llenaHilo();
    }
/**********************************
* Funcion Que hace el auto scroll
**********************************/
    private void addText(String s) {
        texto.append(s);
        texto.getCaret().setDot( texto.getText().length() );
        scrollpnl.scrollRectToVisible(texto.getVisibleRect() );
        //this.paint(this.getGraphics()); // should use "paintImmediately" but not usable for JDialog in 1.2 (should be in 1.3)
    }
/**********************************/

    public static void main(String[] args) {
        new Principal();
    }
    class llenaHilo extends Thread{
        public llenaHilo() {
            start();
        }
        @Override
        public void run() {
            double d = 0;
            while (true) {
                addText("Hola: " + d++ + "\n");
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

0 comentarios: