简体   繁体   中英

Removing And Adding Tons of Items In JList

在此处输入图片说明

The purpose is moving selected items from left to right and vice versa.
With few items works fine, but once it deals with many items like over 20k, it goes so slow.

DefaultListModel<String> fromModel = (DefaultListModel<String>) fromJList.getModel();
DefaultListModel<String> toModel = (DefaultListModel<String>) toJList.getModel();

int selectedIndex;
while ((selectedIndex = fromJList.getSelectedIndex()) != -1)
{
     String itemToRemove = fromModel.remove(selectedIndex);
     fromList.remove(itemToRemove);
     toList.add(itemToRemove);
     toModel.addElement(itemToRemove);
}

DefaultListModel's implementation is not the best for this kind of job. And adding/removing one by one is not efficient too, as it fires refresh event at each call.

Best would be to create your own ListModel by extending AbstractListModel.

https://docs.oracle.com/javase/8/docs/api/javax/swing/AbstractListModel.html

The idea is to do all the updates, add/remove items and then call fireContentsChanged

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