JScrollPane scroll at last added line

浪子不回头ぞ 提交于 2019-12-06 06:42:05
mKorbel

follows link from this thread ScrollPane scroll to bottom problem

Best (and up-to-date, as far as I can tell) explanation of how caret is moved, by Rob Camick:

http://tips4java.wordpress.com/2008/10/22/text-area-scrolling/

Is it possible, that you are not on the EDT? If the append does not happen on the EDT, the position of the JTextArea does not update.

Short, runnable example to show this behaviour:

import java.awt.TextArea;

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


public class Sample {

    public static void main(String[] args) {

        /*
         * Not on EDT
         */
        showAndFillTextArea("Not on EDT", 0, 0);

        /*
         * On EDT
         */
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                showAndFillTextArea("On EDT", 400, 0);
            }
        });
    }

    private static void showAndFillTextArea(String title, int x, int y) {

        JFrame frame = new JFrame(title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextArea textArea = new JTextArea(20, 20);
        JScrollPane scrollPane = new JScrollPane(textArea);
        frame.getContentPane().add(scrollPane);
        frame.pack();
        frame.setLocation(x, y);
        frame.setVisible(true);
        for(int i = 0; i < 50; i++) {
            textArea.append("Line" + i + "\n");
        }
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!