开发者

Unable to programatically scroll to last item in JList

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(getWordListScro开发者_运维问答ller().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);
}


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."


This snippet worked for me

private JList<String> lstDebug;

private void scrollToBottom(){
    int lastIndex = lstDebug.getModel().getSize()-1;
    if(lastIndex >= 0){
        lstDebug.ensureIndexIsVisible(lastIndex);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜