问题
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.
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);
回答1:
This should do it:
dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
回答2:
Or, if multi-selection is enabled :
dataList.scrollRectToVisible(
dataList.getCellBounds(
dataList.getMinSelectionIndex(),
dataList.getMaxSelectionIndex()
)
);
回答3:
You can use the ensureIndexIsVisible
method
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.
来源:https://stackoverflow.com/questions/1543705/java-jlist-scroll-to-selected-item