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?
Try using the JList#ensureIndexIsVisible() method:
JList wordList = getWordListScroller ();
int lastIndex = wordList.getModel().getSize() - 1;
if (lastIndex >= 0) {
wordList.ensureIndexIsVisible(lastIndex);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With