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 J开发者_运维百科List 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);
}
精彩评论