首页javajlistJava Swing - 如何通过DefaultListModel添加,删除JList中的数据

Java Swing - 如何通过DefaultListModel添加,删除JList中的数据

我们想知道如何通过DefaultListModel添加,删除JList中的数据。

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();
  }
}