15

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));
mKorbel
  • 109,525
  • 20
  • 134
  • 319
itro
  • 7,006
  • 27
  • 78
  • 121
  • 1
    Does `WebTextArea` extend `java.awt.TextArea` or `javax.swing.JTextArea`? Please be specific in future posts. It is hard enough debugging code snippets on forums visited by people who speak many different native tongues, to be wondering about the exact classes used. – Andrew Thompson Jan 25 '12 at 10:16

2 Answers2

26

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)

kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • 1
    **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?** – itro Jan 25 '12 at 11:52
17
textArea.setCaretPosition(textArea.getDocument().getLength());
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • 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 Jan 25 '12 at 11:45
  • 1
    @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. – Sh4d0wsPlyr Nov 11 '14 at 22:32