Automatically scroll to the bottom of a text area

itro picture itro · Jan 25, 2012 · Viewed 17.1k times · Source

I have a text area with scroll bar. At regular intervals, I am adding new lines of text to it. I would like the text area to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added. How can I accomplish this?

textAreaStatus = new WebTextArea();
scrollPane = new JScrollPane(textAreaStatus);
textAreaStatus.setBackground(Color.black);
textAreaStatus.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));

Answer

kleopatra picture kleopatra · Jan 25, 2012

Have a look at the updatePolicy property of DefaultCaret: it might do what you want

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

A nice summary of options by Rob (@camickr)