简体   繁体   中英

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.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM