views:

657

answers:

3

Hi,

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?

thanks!

String[] data = {"one", "two", "three", "four", /* AND A LOT MORE */};
JList dataList = new JList(data);
JScrollPane scrollPane = new JScrollPane(dataList);
+6  A: 

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.

Sam Barnum
+2  A: 

Or, if multi-selection is enabled :

dataList.scrollRectToVisible(
        dataList.getCellBounds(
            dataList.getMinSelectionIndex(), 
            dataList.getMaxSelectionIndex()
        )
);
Nate
its dataList.getMinSelectionIndex()however, the answer is still useful for me :)
Fortega
Thanks - edited code from `Selelected` to `Selection`
Nate
+8  A: 

This should do it:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
Sbodd