Home arrow static arrow Java Programming [Archive] - Question about JScrollPane and JTextArea
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Question about JScrollPane and JTextArea
This topic has 4 replies on 1 page.

Posts:23
Registered: 2/20/04
Question about JScrollPane and JTextArea  
Aug 8, 2004 12:51 PM



 
I'm trying to make a chat program with the JScrollPane and JTextArea. However, when I append messages to the JTextArea, the JScrollPane does not automatically scroll down. Is there a method in JScrollPane to let it automatically scroll down when messages are appended to the JTextArea.

Also, it would be convenient to have the JScrollPane auto-scroll only when the scroll bar is already as down as possible. This allows users to view earlier messages without having the JScrollPane scroll down whenever a new message is added. Is there any way to do this?

Thanks.
 

Posts:668
Registered: 9/2/03
Re: Question about JScrollPane and JTextArea  
Aug 8, 2004 1:11 PM (reply 1 of 4)



 
Try this:
JTextArea area = new JTextArea();area.setCaretPosition(area.getText().length);
 

Posts:24,517
Registered: 98-02-27
Re: Question about JScrollPane and JTextArea  
Aug 8, 2004 3:47 PM (reply 2 of 4)



 
I think I've answered this question about 50 times.

Is the search feature broken??

textComponent.setCaretPosition( textComponent.getDocument().getLength() );

is more efficient than the above suggestion.
 

Posts:23
Registered: 2/20/04
Re: Question about JScrollPane and JTextArea  
Aug 8, 2004 4:40 PM (reply 3 of 4)



 
Thanks, but is there also any way to make it only scroll when the scroll bar is already all the way down? This way a user can view older messages without it scrolling down whenever a new message comes in.
 

Posts:6
Registered: 10/9/03
Re: Question about JScrollPane and JTextArea  
Aug 10, 2004 9:49 AM (reply 4 of 4)



 
The following code fragments demonstrate how to auto scroll a JTextArea ("area") that's wrapped in a JScrollPane ("scrollPane"). Auto scrolling is enabled whenever the vertical scrollbar is located at the very bottom of the area. This allows you to scroll back up at leisure (disabling auto scroll) and then drag the vertical scrollbar back to the bottom to re-enable auto scroll:

// 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() );
 
This topic has 4 replies on 1 page.