Java JList scroll to selected item
Asked Answered
P

3

21

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);
Printmaking answered 9/10, 2009 at 13:21 Comment(1)
To make sure it is always visible you can override the setSelectedIndex method and call the Sbodd's method from there.Urolith
I
57

This should do it:

dataList.ensureIndexIsVisible(dataList.getSelectedIndex());
Ineslta answered 9/10, 2009 at 13:30 Comment(0)
N
12

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.

Nutria answered 9/10, 2009 at 13:28 Comment(0)
C
12

Or, if multi-selection is enabled :

dataList.scrollRectToVisible(
        dataList.getCellBounds(
            dataList.getMinSelectionIndex(), 
            dataList.getMaxSelectionIndex()
        )
);
Charlton answered 9/10, 2009 at 13:30 Comment(1)
its dataList.getMinSelectionIndex() however, the answer is still useful for me :)Printmaking

© 2022 - 2024 — McMap. All rights reserved.