Java JList scroll to selected item

javajlistscrollswing

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);

Best Answer

This should do it:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex());