如何将项目从 jlist 复制到另一个项目? [英] how to Copy an item from jlist to another?

查看:32
本文介绍了如何将项目从 jlist 复制到另一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将项目从一个 jlist 复制到另一个 jlist 时遇到问题,我设置了一个按钮动作侦听器代码,它可以工作但不是我想要的.当我选择一个项目并按下按钮时,所选项目的副本将在 jlist2

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);

} 

非常感谢.

推荐答案

如果我正确理解您的意图,您想在按下按钮时将项目复制到 jList2 避免重复,保留之前复制的项目.假设 jList2 使用 DefaultListModel,你可以检查它是否已经包含一个项目:

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);
        }
    }
}

(使用足够新的 java,您还应该使用泛型和 getSelectedValuesList()).

(Using recent enough java, you should also use generics and getSelectedValuesList()).

这篇关于如何将项目从 jlist 复制到另一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆