The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
April 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Re: auto scrolling JTextArea in SWING

Posted by Dave on February 13, 2002 at 10:56 AM

There is a very simple way to force the scroll pane to
scroll down after appending a string to the text.
The point is that the text area is scrolled down after You call
jTextArea.setText( textString ).

So just use:

jTextArea.append( string ); // append the string You want to
jTextArea.setText( jTextArea.getText() );

The second line does not change the text in the text area but
it forces the scroll pane to scroll down the text area.

You can also use

jTextArea.setText( jTextArea.getText() + string );

which is a little bit more effective than the two lines above.



> Move the JScrollPane's vertical scrollBar down after appending the String:

> _pane.getVerticalScrollBar().setValue(_logText.getHeight() - _logText.getVisibleRect().height );

> > I have exactly the same problem, and I have found an answer yet.
> > I have been looking around for a week, but still not found a correct solution.
> > My solution is:
> > private void addText(String s) {
> > _logText.append(s);

> > _logText.getCaret().setDot( _logText.getText().length() );
> > _pane.scrollRectToVisible(_logText.getVisibleRect() );

> > this.paint(this.getGraphics()); // should use "paintImmediately" but not usable for JDialog in 1.2 (should be in 1.3)
> > }

> > where _logText is the JTextArea and and _pane is the JScrollPane using _logText.
> > However this solution is not ideal as it is only scrolling when all the inserts in the JTextArea are finished.
> > If any one has a correct solution, let me know.

> > > Hi,

> > > In the AWT if I create a TextArea and then keep feeding information to that
> > > TextArea, it scrolls automatically to show me to most recently appended text
> > > in the component. However if use the swing equivalent, JTextArea this
> > > doesn't happen even if I wrap this class in a JScrollPane. It does bring up
> > > the scrollbar when text gets too much to fit in the window, but it doesn't
> > > automatically scroll down to show me the latest added text.

> > > Is there anyway I can change this?

> > > Thanks a lot,
> > > Russell


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us