Duel Gamers Duel Gamers - 1 month ago 10
Java Question

Remove obj from scroll able list when selected

I have 2 scroll able lists, list1 and 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.

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

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

Answer Source

You check the equality between the List of Car and a Car:

 if (cars.equals(selectedCar))

It will never be true.

You should rather compare the selected Car with the current Car of the iteration :

 if (eachcar.equals(selectedCar))

After your edit, I think that you need is removing the data from the JList
To do it, use an iterator to remove the selected element in 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); to update the content of the JList.