繁体   English   中英

无法以编程方式滚动到 JList 中的最后一项

[英]Unable to programatically scroll to last item in JList

我有一个嵌套在 JScrollPane 中的 JList。 当我向 JList 添加项目时,我希望 JScrollPane 自动滚动到 JList 的底部,以便最后一个项目可见。 为此,我有以下代码:

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

但是,当我尝试使用此代码时,JScrollPane 仅滚动到倒数第二个项目,而将最后一个项目留在视野之外。 这绝不是可取的。 我尝试向 getMaximum() 添加值,但问题仍然存在。

如何让 JScrollPane 滚动到最底部?

尝试使用JList#ensureIndexIsVisible()方法:

JList wordList = getWordListScroller ();
int lastIndex = wordList.getModel().getSize() - 1;
if (lastIndex >= 0) {
   wordList.ensureIndexIsVisible(lastIndex);
}

虽然这个答案对我不起作用,但我发现这个: http ://forums.sun.com/thread.jspa?threadID=623669(帖子由 'inopia' 撰写)它完美地工作。

正如他所说:“这里的问题是,在 ListModel、JList 和 JScrollPane 都更新后,找到触发的事件会变得有点困难。”

这个片段对我有用

private JList<String> lstDebug;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM