Java Swing How to - Get the Items in a JList from Model








Question

We would like to know how to get the Items in a JList from Model.

Answer

//  ww w .j  ava  2s .  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);

    // Get number of items in the list
    int size = list.getModel().getSize(); // 4

    // Get all item objects
    for (int i = 0; i < size; i++) {
      Object item = list.getModel().getElementAt(i);
    }
  }
}