Automatically scroll to the bottom of a text area

18,012

Solution 1

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)

Solution 2

textArea.setCaretPosition(textArea.getDocument().getLength());
Share:
18,012
itro
Author by

itro

I do software .

Updated on June 14, 2022

Comments

  • itro
    itro almost 2 years

    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));
    
  • itro
    itro over 12 years
    Every time that i add text to taxArea should i call textArea.setCaretPosition(textArea.getDocument().getLength()‌​); ? Is there any other way to do it automatically? Is there any listener for textArea to use?
  • itro
    itro over 12 years
    I get erro in IDE and i put DefaultCaret. to ALWAYS_UPDATE like caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); where should i put this code? when should i call the code that you provideded and where?
  • kleopatra
    kleopatra almost 10 years
    @user3764804 rolled back the edit as it was not necessary - static imports do the magic ;-)
  • Sh4d0wsPlyr
    Sh4d0wsPlyr over 9 years
    @itro - Why not add a function to add text. For example, I have a function to add text to my text area. Simple matter of adding an extra line to my function to update it automatically.