简体   繁体   English

如何将项目从jlist复制到另一个?

[英]how to Copy an item from jlist to another?

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. 我将项目从一个jlist复制到另一个jlist时遇到问题,我设置了一个按钮操作侦听器代码,它可以正常工作,但并不能满足我的需要。 When I select an item and I press the button, a copy of the selected item will be in jlist2 当我选择一个项目并按下按钮时,所选项目的副本将位于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. 如果我理解正确你的意图,要项目复制到jList2当按钮被按下, 避免重复, 保持已较早复制的项目。 Assuming jList2 uses DefaultListModel , you can check if it already contains an item: 假设jList2使用DefaultListModel ,则可以检查它是否已经包含一个项目:

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() ). (使用最新的Java,您还应该使用泛型和getSelectedValuesList() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM