views:

56

answers:

2

Hello community! 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!

+4  A: 

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.

Syntax
Thank you very much! it worked as I needed!
Juan Diego
+1  A: 

I haven't tested this, but you should be able to use

myScrollPane.getViewport().scrollRectToVisible(Rectangle r)

where r is an area of your JList's total (virtual) area that contains the information of interest. You can calculate the required vertical offset from the JList's item height and the row number.


EDIT: Syntax's answer is even easier to implement.

Carl Smotricz
+1 Indeed, `JList` uses `scrollRectToVisible()` to implement `ensureIndexIsVisible()`.
trashgod
Thank you Carl!
Juan Diego