I have a problem with copying items from one jlist to another, I set a button action listener code, it works but not as i want. When I select an item and I press the button, a copy of the selected item will be in jlist2
But the problem is if I select the same item and click the button the item will be shown twice and this is no expected.
This is the code, please help as soon as possible.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
int[] selectedIx = jList1.getSelectedIndices();
DefaultListModel lm = new DefaultListModel();
ListModel list = jList2.getModel();
for (int i = 0; i < list.getSize(); i++) {
Object prev = list.getElementAt(i);
lm.addElement(prev);
}
for (int i = 0; i < selectedIx.length; i++) {
Object sel = jList1.getModel().getElementAt(selectedIx[i]);
lm.addElement(sel);
}
jList2.setModel(lm);
}
thanks alot.
原因是您将元素两次添加到DefaultListModel中。
Object prev and Object sel
do like this
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
List<String> selectedValuesList = jList1.getSelectedValuesList();
jList2.setListData(selectedValuesList.toArray(new String[selectedValuesList.size()]));
}
If I understood your intent correctly, you want to copy items to jList2
when the button is pressed, and avoid duplicates, and keep the items that have been copied earlier. Assuming jList2
uses DefaultListModel
, you can check if it already contains an item:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel list = (DefaultListModel) jList2.getModel();
for (Object sel : jList1.getSelectedValues()) {
if (list.indexOf(sel) == -1) {
list.addElement(sel);
}
}
}
(Using recent enough java, you should also use generics and getSelectedValuesList()
).
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.