Java JList scroll to selected item

Fortega picture Fortega · Oct 9, 2009 · Viewed 21.8k times · Source

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

Answer

Sbodd picture Sbodd · Oct 9, 2009

This should do it:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex());