请问如何保持列表框中的元素的唯一性呢?例如,我有两个列表框(好像MSN添加删除联系人的列表框那样)当我点击了“添加”之后,左边被选中的元素就会添加到右边的列表框里面,但是如果右边的列表框已经存在了被选的元素,就不能再添加,请问这个功能怎样实现啊?谢谢~ 

解决方案 »

  1.   

    这种处理方法最好是左侧和右侧的JList中的元素都使用一个HashMap map或者LinkedList list保存.
    1.按钮监听中实现遍历右侧数据结构list
    2.在遍历中判定是否存在左侧待添加元素(也就是左侧JList的getSelectedValue());
    3.此处设置一个flag = true,在(2)的遍历中若有相同元素则flag=false
    4.添加到左侧JList的操作代码以if(flag){}作为判别条件,也就是存在相同元素不进行添加。刚好这两天帮别人写了段类似代码,我就只贴出ActionListener里面的实现了,如下:if("转换".equals(((JButton)(e.getSource())).getText())){
    boolean flag = true;
    boolean execute = true;
    Product pro = null;
    for(int i=0;i<InfoCreate.inventory.size();i++){
    if(productList.getSelectedValue().equals(InfoCreate.inventory.get(i).getName())){
    execute = false;
    }
    }
    if(execute){
    try{
            Integer.parseInt(numText.getText());
    }catch(Exception ex){
    flag = false;
    }
    if(flag){
    for(int i=0;i<InfoCreate.products.size();i++){
    if(InfoCreate.products.get(i).getName().equals(productList.getSelectedValue())){
    pro = InfoCreate.products.get(i);
    }
    }
    MaterialsInventory newMater = new MaterialsInventory(InfoCreate.inventory.size()+1,pro.getName(),pro.getDescribe(),Integer.parseInt(numText.getText()));
    InfoCreate.inventory.add(newMater);
    meterialsListModel.addElement(newMater.getName());
    }
    }
    上面的这段代码是实现我程序里面的“产品”向“原材料”的转换操作,Swing视图表示和你的结构一样,里面的静态变量含义就不解释了.
      

  2.   


    右面数据是存在一个java.util.list里面吧,
    如果是的,用List里面的contains方法判断一下有没有就行了,
    很方便。
    顶多重写一下equalsgood luck