Listening for Changes to the Items in a JList Component : JList Selection « Swing « Java Tutorial






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








14.43.JList Selection
14.43.1.List selection event
14.43.2.A single-selection JList.
14.43.3.Listening for Changes to the Items in a JList Component
14.43.4.Listening for Changes to the Selection in a JList Component
14.43.5.Setting the Selection Mode of a JList Component
14.43.6.The selected items must be in a contiguous range
14.43.7.Multiple ranges of selected items are allowed
14.43.8.Setting the Selected Items in a JList Component
14.43.9.Select all the items
14.43.10.Clear all selections
14.43.11.Select the first item
14.43.12.Add another selection - the third item
14.43.13.Deselect the first item
14.43.14.Getting the Selected Items in a JList Component
14.43.15.Get the index of the last selected item
14.43.16.Determine if there are any selected items