Add listener to ArrayList

Eng.Fouad picture Eng.Fouad · Jul 5, 2011 · Viewed 36.9k times · Source

I have an ArrayList which I add some Objects to it dynamically, and I have a JButton. The ArrayList is empty when running my program and the JButton is set to setEnabled(false). I want to enable my button whenever there are 2 elements in the ArrayList or more and disable it again if the ArrayList has one item or empty. How can I achieve this?

Answer

Jon Skeet picture Jon Skeet · Jul 5, 2011

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.