I have a chat box style JTextArea which sits inside a JScrollPane. When something is added to the JTextArea, I scroll the JScrollPane speechScroll to the bottom using a method which was discussed in http://forums.sun.com/thread.jspa?forumID=57&threadID=393636 :
public void scrollPaneToBottom() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
speechScroll.getVerticalScrollBar().setValue(
speechScroll.getVerticalScrollBar().getMaximum());
}
});
}
This usually works. Except sometimes it doesn't.
On some occasions, there is no effect to calling the scrollPaneToBottom() method. The place that speechScroll is scrolled to remains the same.
I have especially noticed this on the occasions when I have to both scroll to the bottom of speechScroll and to enable and set focus to another component (a JTextField into which users type the answer to the question that should have just appeared in speechScroll), but even then it is not consistent. Sometimes it scrolls and sometimes it doesn't, and I don't see any pattern to when it does or doesn't.
In an attempt at a hack to see the problem solved, I have tried calling the scroll to bottom both before and after enabling/focusing to the JTextField, despite the fact that this should be redundant, and I saw a reduction in the number of times that it did not scroll, but on some occasions it did still fail to scroll.
Does anyone have any idea what is causing this failure to scroll and what I can do to ensure that it scrolls every time?
Thank you!