Listening for Changes to the Items in a JList Component

When the set of items in a list component is changed, a list data event is fired.
// Create a list that allows adds and removes; // see Adding and Removing an Item in a JList Component // Register a list data listener DefaultListModel model = (DefaultListModel)list.getModel(); model.addListDataListener(new MyListDataListener()); class MyListDataListener implements ListDataListener { // This method is called when new items have been added to the list public void intervalAdded(ListDataEvent evt) { DefaultListModel model = (DefaultListModel)evt.getSource(); // Get range of new items int start = evt.getIndex0(); int end = evt.getIndex1(); int count = end-start+1; // Get new items for (int i=start; i<=end; i++) { Object item = model.getElementAt(i); } } // This method is called when items have been removed from the list public void intervalRemoved(ListDataEvent evt) { // Get range of removed items int start = evt.getIndex0(); int end = evt.getIndex1(); int count = end-start+1; // The removed items are not available } // This method is called when items in the list are replaced public void contentsChanged(ListDataEvent evt) { DefaultListModel model = (DefaultListModel)evt.getSource(); // Get range of changed items int start = evt.getIndex0(); int end = evt.getIndex1(); int count = end-start+1; // Get changed items for (int i=start; i<=end; i++) { Object item = model.getElementAt(i); } } }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.