开发者

Java Swing: Autoscrolling using JList and JScrollPane

开发者 https://www.devze.com 2023-01-06 08:50 出处:网络
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 wi

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开发者_如何学Go on the JList.

Thank you in advance!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号