Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to programatically scroll to last item in JList

Tags:

java

swing

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?

like image 723
Chris Lieb Avatar asked Apr 23 '10 02:04

Chris Lieb


1 Answers

Try using the JList#ensureIndexIsVisible() method:

JList wordList = getWordListScroller ();
int lastIndex = wordList.getModel().getSize() - 1;
if (lastIndex >= 0) {
   wordList.ensureIndexIsVisible(lastIndex);
}
like image 115
RTBarnard Avatar answered Oct 13 '22 10:10

RTBarnard