简体   繁体   中英

How to transfer the elements from one JList to other JList in Java?

I have two JList on a swing GUI. Now I want that when a user clicks on a button (say TransferButton) the selected elements from one JList is added from the first JList to the second JList and remove those selected elements from the first JList.

The model doesn't know about selection.

The JList provides several methods to get the selected item or selected index. Use those methods to get the items and add them to the other list's model.

You have two JList s, then you also have their respective ListModel s. Depending on how you implemented them you can just remove the elements from one model and add them to the other. Note, though, that the ListModel interface doesn't care for more than element access by default, so you probably have to implement add and remove methods there by yourself.

DefaultListModel leftModel = new DefaultListModel();
leftModel.addElement("Element 1");
leftModel.addElement("Element 2");
leftModel.addElement("Element 3");
leftModel.addElement("Element 5");
leftModel.addElement("Element 6");
leftModel.addElement("Element 7");

JList leftList = new JList(leftModel);

DefaultListModel rightModel = new DefaultListModel();
JList rightList = new JList(rightModel);

Let's imagine you have two JList components as described in the code above (left and right). You must write following code to transfer selected values from the left to the right JList.

for(Object selectedValue:leftList.getSelectedValuesList()){
    rightModel.addElement(selectedValue);
    leftModel.removeElement(selectedValue);
}

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