Java JList 滚动到所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1543705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java JList scroll to selected item
提问by Fortega
I have a JList
with a lot of items in it, of which one is selected. I would like to scroll to the selected item in this JList
, so the user can quickly see which item is selected.
我有一个里面JList
有很多项目,其中一个被选中。我想在 this 中滚动到所选项目JList
,以便用户可以快速查看选择了哪个项目。
How can I do this?
我怎样才能做到这一点?
String[] data = {"one", "two", "three", "four", /* AND A LOT MORE */};
JList dataList = new JList(data);
JScrollPane scrollPane = new JScrollPane(dataList);
采纳答案by Sbodd
This should do it:
这应该这样做:
dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
回答by Sam Barnum
You can use the ensureIndexIsVisible
method
您可以使用该ensureIndexIsVisible
方法
http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#ensureIndexIsVisible(int)
http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#ensureIndexIsVisible(int)
Scrolls the list within an enclosing viewport to make the specified cell completely visible. This calls scrollRectToVisible with the bounds of the specified cell. For this method to work, the JList must be within a JViewport.
在封闭视口内滚动列表以使指定的单元格完全可见。这将使用指定单元格的边界调用 scrollRectToVisible。要使此方法起作用,JList 必须位于 JViewport 内。
回答by Nate
Or, if multi-selection is enabled :
或者,如果启用了多选:
dataList.scrollRectToVisible(
dataList.getCellBounds(
dataList.getMinSelectionIndex(),
dataList.getMaxSelectionIndex()
)
);