Java JList scroll to selected item

柔情痞子 提交于 2019-12-04 15:49:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!