Add listener to ArrayList

You can't do such thing with ArrayList because as @Jon Skeet says ArrayList doesn't have any sort of notification mechanism. You should try JGoodies binding ObservableList that could help.

Or you could set up a timer that will check for the size of ArrayList and change JButton accordingly. You will require a thread to do this job of monitoring list at some time interval.

Or if you know all the place where you add/remove elements from list then write this login at all that place.


As @Jon Skeet suggests you can also do something like :

public class ListResponseModel<E> extends AbstractListModel {

    private static final long serialVersionUID = 1L;

    private ArrayList<E> delegate = new ArrayList<E>();

    @Override
    public int getSize() {
        return delegate.size();
    }

    @Override
    public Object getElementAt(int index) {
        return delegate.get(index);
    }

    public void add(E e){
        int index = delegate.size();
        delegate.add(e);
        fireIntervalAdded(this, index, index);
    }
}

ArrayList doesn't have any sort of notification mechanism.

I suggest you write your own List implementation which delegates to a private ArrayList for its storage, but adds the ability to listen for notifications... or find something similar within Java itself. DefaultListModel may work for you, although it doesn't implement List itself.


Javafx (part of JRE 8) provides an observable list implementation. This code works for me:

ObservableList<MyAnno> lstAnno1 = FXCollections.observableList(new ArrayList<MyAnno>());

lstAnno1.addListener((ListChangeListener.Change<? extends MyAnno> c) -> {
   c.next();
   updateAnnotation((List<MyAnno>) c.getAddedSubList(), xyPlot);
});

...
lstAnno1.add(new MyAnno(lTs, dValue, strType));
...

public void updateAnnotation(List<MyAnno> lstMyAnno, XYPlot xyPlot) {
   lstMyAnno.forEach(d -> {
   ...
   });
}