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?
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(); });
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.
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.
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.
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 -> {
...
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With