This tutorial will describe how you can use a single line of code to make a JTextArea scroll down to the bottom of the text area automatically as text is appended to it. This is excellent for applications such as; network clients and servers that must display massive amounts of text data as well as any application that requires adding data to a log that is visible at all times.

In this example the JTextArea will be referred to as “TextArea.” The magic line of code is highlighted below:

TextArea.setCaretPosition(TextArea.getText().length() – 1);

All you need to do now is add this line below every TextArea.append(); command. An example is below:

TextArea.append(textString);

TextArea.setCaretPosition(TextArea.getText().length() – 1);

The setCaretPosition() method can be used when using the setText() method on a JTextArea also. There may also be further uses for the setCaretPosition() method, however, I have not yet needed them, but if you find them, well done!

This is a very common question and it just made sense to give it a quick and simple answer. Hopefully this has solved your problem. Good luck with your program!

Advertisements