Search code examples
javaswingjlistjscrollpane

Java Swing: Autoscrolling using JList and JScrollPane


I'm having this problem:

I have a JList (within a JScrollPane) with say about 1000 elements, and the dimensions of this JList obviously doesn't allow to show all the data. Now, I have this JList within a JScrollPane and I need that when I say JList.setSelectedIndex(), the JScrollPane automatically scrolls into, and show that element on that index on the JList.

Thank you in advance!


Solution

  • I believe you are looking for the following method:

    public void ensureIndexIsVisible(int index)

    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. If the given index is outside the list's range of cells, this method results in nothing.