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