Search code examples
javaswingjscrollpanejtextarea

Lock JScrollPane to bottom of JTextArea (java swing)


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.


Solution

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

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