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,其中一个被选中。我想滚动到此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);
3 个解决方案
#1
48
This should do it:
这应该这样做:
dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
#2
10
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中。
#3
10
Or, if multi-selection is enabled :
或者,如果启用了多选:
dataList.scrollRectToVisible(
dataList.getCellBounds(
dataList.getMinSelectionIndex(),
dataList.getMaxSelectionIndex()
)
);
#1
48
This should do it:
这应该这样做:
dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
#2
10
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中。
#3
10
Or, if multi-selection is enabled :
或者,如果启用了多选:
dataList.scrollRectToVisible(
dataList.getCellBounds(
dataList.getMinSelectionIndex(),
dataList.getMaxSelectionIndex()
)
);