tags:

views:

88

answers:

2

I have a JList nested inside of a JScrollPane. When I add items to the JList, I want the JScrollPane to automatically scroll to the bottom of the JList so the last item is visible. To do this, I have the following code:

getWordListScroller().getVerticalScrollBar().getModel().setValue(getWordListScroller().getVerticalScrollBar().getModel().getMaximum());

When I try using this code, however, the JScrollPane only scrolls to the second to last item, leaving the last item out of view. This is not in any way desirable. I've tried adding values to getMaximum(), but the issue persists.

How can I get the JScrollPane to scroll to the very bottom?

+1  A: 

Try using the JList#ensureIndexIsVisible() method:

JList wordList = getWordListScroller ();
int lastIndex = wordList.getModel().getSize() - 1;
if (lastIndex >= 0) {
   wordList.ensureIndexIsVisible(lastIndex);
}
RTBarnard
I just found that myself and it works beautifully.
Chris Lieb
A: 

While this answer didn't work for me, I found this: http://forums.sun.com/thread.jspa?threadID=623669 (post written by 'inopia') Which works perfectly.

As he says: "The problem here is that it can become a bit difficult to find an event that fires after both the ListModel, JList and JScrollPane have been updated."

mohsenof