Java Swing How to - Get index of first visible item








Question

We would like to know how to get index of first visible item.

Answer

//from ww w. ja v  a  2 s .c  o m

import javax.swing.JList;

public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);

    int itemIx = list.getFirstVisibleIndex();
    if (itemIx < 0) {
      // List is either not visible or there are no items
    }
  }
}