I'm working on a JavaFX app and am using a TableView as part of the GUI as follows:
public TableView<Meal> meals;
And to it I assigned a button that is supposed to delete elements which are selected. To do that I used a function that kept giving me a NoSuchElementException
public void deleteMealButtonClicked()
{
ObservableList<Meal> mealsSelected = meals.getSelectionModel().getSelectedItems();
ObservableList<Meal> allMeals = meals.getItems();
mealsSelected.forEach(allMeals::remove);
}
I debugged my way into finding out the problem was in the last line of the method.
After researching for quite a while, I happened to stumble across a piece of code that solved the problem. Here is the method with the code that works:
public void deleteMealButtonClicked()
{
ObservableList<Meal> mealsSelected = meals.getSelectionModel().getSelectedItems();
ObservableList<Meal> allMeals = meals.getItems();
if (mealsSelected != null) {
ArrayList<Meal> rows = new ArrayList<>(mealsSelected);
rows.forEach(row -> meals.getItems().remove(row));
}
}
My question is, why does the second method work and not the first? Aren't they fundamentally the same thing, other than adding the selected rows to an ArrayList on the second method?
Thank you in advance.