Java Swing How to - Handle List data event








Question

We would like to know how to handle List data event.

Answer

/*from   www.  j  a v a  2  s .co m*/
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class Main {
  public static void main(String[] argv) throws Exception {
    JList list = new JList();
    // Register a list data listener
    DefaultListModel model = (DefaultListModel) list.getModel();
    model.addListDataListener(new MyListDataListener());
  }
}

class MyListDataListener implements ListDataListener {
  public void intervalAdded(ListDataEvent evt) {
    DefaultListModel model = (DefaultListModel) evt.getSource();
    int start = evt.getIndex0();
    int end = evt.getIndex1();
    int count = end - start + 1;

    for (int i = start; i <= end; i++) {
      Object item = model.getElementAt(i);
    }
  }
  public void intervalRemoved(ListDataEvent evt) {
    int start = evt.getIndex0();
    int end = evt.getIndex1();
    int count = end - start + 1;
  }
  public void contentsChanged(ListDataEvent evt) {
    DefaultListModel model = (DefaultListModel) evt.getSource();
    int start = evt.getIndex0();
    int end = evt.getIndex1();
    int count = end - start + 1;
    for (int i = start; i <= end; i++) {
      Object item = model.getElementAt(i);
    }
  }
}