简体   繁体   English

选择时从可滚动列表中删除obj

[英]Remove obj from scroll able list when selected

I have 2 scroll able lists, list1 and list2. 我有2个可滚动列表,分别为list1和list2。

Both with same objects on the lists but I need to remove the obj from list 2 when it is selected in list 1. 两者在列表上具有相同的对象,但是当在列表1中选择它时,我需要从列表2中删除obj。

This is my Code: 这是我的代码:

   private void displayList2()
   {
      Car selectedCar = (Car)list1.getSelectedValue(); //gets the selected value from list1 which is working fine.
      List<String> carsData = new ArrayList<String>();
      for (Car eachcar : cars)
      {
          if (cars.equals(selectedCar))
          {
              list2.remove(selectedCar);
          }
      }
   }

It currently getSelectedValue from a scrollable list (list1) which works fine but it does not remove from list 2 目前,它从可滚动列表(list1)中获取getSelectedValue,效果很好,但不会从列表2中删除

EDIT: 编辑:

I have now altered the code a bit to look like this but still does not work: 我现在对代码进行了一些更改,使其看起来像这样,但仍然无法正常工作:

   private void displayList2()
       {
          Car selectedCar = (Car)list1.getSelectedValue(); //gets the selected value from list1 which is working fine.
          List<String> carsData = new ArrayList<String>();
          for (Car eachcar : cars)
          {
              if (carsData.equals(selectedCar))
              {
              carsData.remove(selectedCar);
          }
      list2.setListData(cars);
      }
      list2.setSelectedIndex(0);
   }

There are no errors being displayed and both scroll able lists works and the selectedIndex is at 0 but when clicking on the list1 it still does not remove the object from list2 没有显示任何错误,并且两个滚动列表都可以工作,并且selectedIndex为0,但是单击list1时,它仍然不会从list2中删除该对象。

You check the equality between the List of Car and a Car : 您检查之间的平等ListCarCar

 if (cars.equals(selectedCar))

It will never be true . 永远不会是true

You should rather compare the selected Car with the current Car of the iteration : 您应该将所选的Car与迭代的当前Car进行比较:

 if (eachcar.equals(selectedCar))

After your edit, I think that you need is removing the data from the JList 编辑后,我认为您需要从JList中删除数据
To do it, use an iterator to remove the selected element in cars : 为此,请使用迭代器删除cars中的选定元素:

 for (Iterator<Car> it = cars.iterator(); it.hasNext();){
     Car eachcar = it.next();
     if (eachcar.equals(selectedCar)){
        it.remove();
     }
 }

Then after the loop, invoke list2.setListData(cars); 然后在循环之后,调用list2.setListData(cars); to update the content of the JList. 更新JList的内容。

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

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