4

I currently have a setup where I have a JTextArea inside a JScrollPane so that you can scroll though the text in the box.

What I would like to do is set the JScrollPane up so that whenever new text is added to the box (always at the bottom on a new line) it will scroll down to the bottom.

Is there a simple way to achieve this?

Please note: I don't want it to be permanently locked onto the bottom (users should still be able to scroll through the text), just when text is being updated. I'm after an effect like when you tail a log file in UNIX.

3 Answers3

8

Why not simply set the caret position to the end of the JTextArea. i.e.,

myTextArea.setCaretPosition(myTextArea.getDocument().getLength());
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    +1 [Text Area Scrolling](http://tips4java.wordpress.com/2008/10/22/text-area-scrolling/) offers convenient alternatives, but this might be the easiest way to control scrolling as suggested [here](http://stackoverflow.com/questions/7938881/lock-jscrollpane-to-bottom-of-jtextarea-java-swing/7939508#7939508). – trashgod Oct 29 '11 at 14:35
3

I don't want it to be permanently locked onto the bottom

This example uses an AdjustmentListener to suspend auto-scrolling when the mouse is held down in the scroll bar's thumb. As soon as the thumb is released, auto-scrolling resumes. You can adapt this to JTextArea using the approach suggested by @Hovercraft.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

I use this code and JTextArea go to the bottom on adding text

((DefaultCaret) jTextArea1.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
FaezJana
  • 11
  • 3