Java Swing How to - Add, remove data in JList via DefaultListModel








Question

We would like to know how to add, remove data in JList via DefaultListModel.

Answer

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

import javax.swing.DefaultListModel;
import javax.swing.JList;

public class Main {
  public static void main(String[] argv) throws Exception {
    DefaultListModel<String> model = new DefaultListModel<>();
    JList<String> list = new JList<>(model);

    int pos = 0;
    model.add(pos, "a");

    //Insert an item at the beginning
    model.add(pos, "a");

    // Initialize the list with items
    String[] items = { "A", "B", "C", "D" };
    for (int i = 0; i < items.length; i++) {
      model.add(i, items[i]);
    }

    // Replace the 2nd item
    pos = 1;
    model.set(pos, "b");

    // Remove the first item
    model.remove(pos);

    // Remove the last item
    pos = model.getSize() - 1;
    if (pos >= 0) {
      model.remove(pos);
    }

    // Remove all items
    model.clear();
  }
}