Sorting DefaultListModel

jerome picture jerome · Nov 19, 2012 · Viewed 7.9k times · Source

I would like to sort my DefaultListModel and have it to fire the contents changed event, but I'm stuck with it, and don't understand how can I call its fireContentsChanged method. I see that if my model extends AbstractListModel I can directly call the fireContentsChanged after the sorting, but in the way I did my class with the DefaultListModel, I can't call its fireContentsChanged cause it has protected access. Do I have to extends AbstractListModel or is there a way to call the DefaultListModel fireContentsChanged ?

public class DefaultDataModel implements DataModel 
{
  private DefaultListModel<Data> dataModel = new DefaultListModel<>();
  @Override
  public void addElement(Data data) {
    dataModel.addElement(data);
  }
  @Override
  public int getSize() {
    return dataModel.getSize();
  }
  @Override
  public Data getElementAt(int idx) {
    return dataModel.getElementAt(idx);
  }
  @Override
  public void addListDataListener(ListDataListener l) {
    dataModel.addListDataListener(l);
  }
  @Override
  public int indexOf(Data data) {
    return dataModel.indexOf(data);
  }
  @Override
  public List<Data> getAllData() {
    return Collections.list(dataModel.elements());
  }
  @Override
  public void sort() {
    Collections.sort(getAllData());
  }
}

Answer

jerome picture jerome · Nov 20, 2012

I found how to do it in the sort method I have to call the contentsChanged method from the dataModel listeners list.

@Override
public void sort() {
    Collections.sort(getAllData());
    ListDataListener[] listeners = dataModel.getListDataListeners();
    for(ListDataListener listener : listener) {
        listener.contentsChanged(dataModel, ListDataEvent.CONTENTS_CHANGED, 0, getSize());
    }
}