Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: Approach for dynamically appending text in text area, have scrollbar update

Tags:

java

swing

What is the general approach with Java swing to update a textarea with lines of text (say from a Thread) and then have the text caret flow to the bottom of the textarea as text is being added. Also update the scrollbar so that it is at the bottom.

I was thinking that I would have a stringbuffer and append text to that and then set the string in the textarea and position the scrollbar at the bottom.

like image 685
Berlin Brown Avatar asked Jun 11 '09 20:06

Berlin Brown


2 Answers

Use append() to add the text, then setCaretPosition() to make sure you scroll with it.

myTextPane.append(textFromSomewhere);
myTextPane.setCaretPosition(myTextPane.getDocument().getLength());
like image 56
Michael Myers Avatar answered Oct 12 '22 08:10

Michael Myers


The append() method doesn't do what you want?

And although you didn't ask: when you're generating something in a background thread, be sure to use SwingUtilities.invokeLater() to update your components.

like image 25
kdgregory Avatar answered Oct 12 '22 09:10

kdgregory