javaswingarraylistjlist

How to add all the elements from a JList to an ArrayList?


I have a JList with products, and I need to know how to push all those elements to an ArrayList. How can I do that?

I tried to use addAll method from ArrayList but it didn't work.


Solution

  • We have to iterate through the elements from the ListModel and add each of them to the ArrayList.

    Assuming we have a JList<Product> jList, we can do the following:

    List<Product> products = new ArrayList<>();
    ListModel<Product> jListModel = jList.getModel();
    for (int i = 0; i < jListModel.getSize(); i++) {
        products.add(jListModel.getElementAt(i));
    }