开发者

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

开发者 https://www.devze.com 2022-12-17 01:09 出处:网络
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 JLi

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 JLists, then you also have their respective ListModels. 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消