Reputation: 34735
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.
Upvotes: 0
Views: 4167
Reputation: 31
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);
}
Upvotes: 2
Reputation: 46
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.
Upvotes: 3
Reputation: 354426
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.
Upvotes: 2