Java Swing - how to scroll down a JTextArea?

F. P. picture F. P. · Jun 5, 2011 · Viewed 9.5k times · Source

I have an application with basic chat. I use JTextArea for the buffer. After adding a message I want to scroll to the bottom. How can this be achieved?

I found no member function that would allow me to do this.

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Jun 5, 2011

You can do this by setting the caret position to the end of the text area, i.e.,

myTextArea.setCaretPosition(myTextArea.getDocument().getLength());

Edit: you can find out a lot more on this question by looking at the related questions listed on the lower right of this page. In particular, please check out camickr's answer and link in this thread: How to set AUTO-SCROLLING of JTextArea in Java GUI?. It's a far better and more complete answer than the one I've given (and I've just now up-voted it for this).