Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JScrollPane - scroll tracking

 
Protorium Exodious
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hiya, Im using a JTextArea and adding a JScrollPane to it using new JScrollPane(clientConsole) where clientConsole is the JTextArea
When the textarea fills up, I have to manually scroll down to see new text being added, how can I make it automatically scroll down
Im using it for my chat program - first go at Java so still inexperienced - its the last thing I need to do though
thx for any help
 
Jeff Wisard
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:
Whenever you add text to your text area (i.e. when you call the setText() method), set the caret position of the JTextArea also.
clientConsole.setCaretPosition(clientConsole.getText().length());
This will move make the JScrollPane scroll to the bottom of the JTextArea.
An easy way to do this is to add a DocumentListener to your JTextArea. When the text of the JTextArea changes, the listener is called. Set the caret position in the listener and then you never need to worry about it again.

clientConsole.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
clientConsole.setCaretPosition(clientConsole.getText().length());
}

public void insertUpdate(DocumentEvent e){}
public void removeUpdate(DocumentEvent e){}
});

Hope this helps!
-Jeff
[ January 14, 2002: Message edited by: Jeff Wisard ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic