Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add listener to ArrayList

Tags:

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?

like image 951
Eng.Fouad Avatar asked Jul 05 '11 05:07

Eng.Fouad


People also ask

How do you add a listener to an ArrayList in Java?

In this case the observable is the size of the array, then, when declaring your arraylist, you can add a listener and act when the size is 2. ArrayListProperty<Object> arrayList = new ArrayListProperty<>(); arrayList. addListener((ob, ov, nv) -> { if(nv. intValue() == 2) doSomething(); });

How do you append to an ArrayList?

If you have an arraylist of String called 'foo', you can easily append (add) it to another ArrayList, 'list', using the following method: ArrayList<String> list = new ArrayList<String>(); list. addAll(foo); that way you don't even need to loop through anything.

Can you add to an ArrayList in Java?

To add an object to the ArrayList, we call the add() method on the ArrayList, passing a pointer to the object we want to store. This code adds pointers to three String objects to the ArrayList... list. add( "Easy" ); // Add three strings to the ArrayList list.

How do you declare an ArrayList Java?

The general syntax of this method is:ArrayList<data_type> list_name = new ArrayList<>(); For Example, you can create a generic ArrayList of type String using the following statement. ArrayList<String> arraylist = new ArrayList<>(); This will create an empty ArrayList named 'arraylist' of type String.


2 Answers

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 -> {
   ...
   });
}
like image 107
Michael Baldauf Avatar answered Oct 08 '22 02:10

Michael Baldauf


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.

like image 23
Jon Skeet Avatar answered Oct 08 '22 02:10

Jon Skeet