문제

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 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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top