Autoscroll Text Area

Is it possible to autoscroll the text area component to the end if more text is added to it? In Java, I used to be able to do:

JTextArea area = new JTextArea();
area.setCaretPosition( area.getDocument().getLength() );

Thanks!

Oh man, you already know how to do it in Java? You’re in luck - you can do all of that same stuff through Jython.

The only trick is that the “Text Area” component is actually a JScrollPane with a JTextArea in it.

So you’d do it like this:

scrollPane = ... (grab the text area) area = scrollPane.viewport.view area.setCaretPosition(area.getDocument().getLength())

I tried the code in a property change event for the text area so when new text would be added it would auto scroll.

if( event.propertyName == 'text' ):
    scrollPane = event.source
    area = scrollPane.viewport.view
    area.setCaretPosition( area.getDocument().getLength() )

It does not throw any errors, but does not scroll the text area. I know the script runs since I had inserted a simple print statement to check for sure. Ideas?

Yeah, you probably need to wrap your code in an invokeLater call to ensure it occurs after the text area itself has actually responded to the new text being added.

if( event.propertyName == 'text' ): def doScroll(scrollPane = event.source): area = scrollPane.viewport.view area.setCaretPosition( area.getDocument().getLength() ) system.util.invokeLater(doScroll)

Yep, worked perfectly. I keep forgetting about invokeLater.

Thanks!