21

我有一个JList里面有很多项目,其中一个被选中。我想滚动到 this 中选择的项目JList,以便用户可以快速查看选择了哪个项目。

我怎样才能做到这一点?

String[] data = {"one", "two", "three", "four", /* AND A LOT MORE */};
JList dataList = new JList(data);
JScrollPane scrollPane = new JScrollPane(dataList);
4

3 回答 3

57

这应该这样做:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
于 2009-10-09T13:30:32.720 回答
12

或者,如果启用了多选:

dataList.scrollRectToVisible(
        dataList.getCellBounds(
            dataList.getMinSelectionIndex(), 
            dataList.getMaxSelectionIndex()
        )
);
于 2009-10-09T13:30:17.953 回答
11

您可以使用该ensureIndexIsVisible方法

http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#ensureIndexIsVisible(int)

在封闭的视口中滚动列表以使指定的单元格完全可见。这使用指定单元格的边界调用 scrollRectToVisible。要使此方法起作用,JList 必须位于 JViewport 内。

于 2009-10-09T13:28:37.427 回答