Eng.Fouad Eng.Fouad - 3 months ago 6
Java Question

Add listener to ArrayList

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?


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.