There are some cases where you want a text field to automatically scroll down, e.g. for a log window. The following code snippet will make the JTextArea (embedded in a JScrollPane) scroll down automatically when the scroll position is at the bottom before adding the text:

// Determine whether the scrollbar is currently at the very bottom position.
JScrollBar vbar = scrollPane.getVerticalScrollBar();
boolean autoScroll = ((vbar.getValue() + vbar.getVisibleAmount()) == vbar.getMaximum());

// append to the JTextArea (that’s wrapped in a JScrollPane named ’scrollPane’
area.append( “blah blah\n );

// now scroll if we were already at the bottom.
if( autoScroll ) area.setCaretPosition( area.getDocument().getLength() );

Thanks Udo Schuermann from the Java Forums.

Are you interested in reading more from CodingClues?
Then subscribe to new postings via RSS or via E-Mail.

Viewing 1 Comment

close Reblog this comment
blog comments powered by Disqus