Listening for Changes to the Items in a JList Component
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
publicclass Main {
publicstaticvoid 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 {
publicvoid 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);
}
}
publicvoid intervalRemoved(ListDataEvent evt) {
int start = evt.getIndex0();
int end = evt.getIndex1();
int count = end - start + 1;
}
publicvoid 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);
}
}
}