Question

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);
Was it helpful?

Solution

This should do it:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex());

OTHER TIPS

Or, if multi-selection is enabled :

dataList.scrollRectToVisible(
        dataList.getCellBounds(
            dataList.getMinSelectionIndex(), 
            dataList.getMaxSelectionIndex()
        )
);

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top