This discussion is archived
3 Replies Latest reply: Jan 23, 2013 7:30 AM by sselvia RSS

TableView Remove Item Error

sselvia Newbie
Currently Being Moderated
I am removing selected items from a table view, the table view is a list of maps since my columns are dynamic based on a sql query. I perform the following code the number of rows removed from the table view is not what I expect. I highlight 2 rows and only one is removed when Method 1 is executed, I noticed in the debugger for every item removed from the table view getItems remove method, 2 items are removed from the selected items. When I execute Method 2, then ALL of the items are removed from the table view.

I'm using the JDK 7 update 10.

Method 1:

List<Map> items = tblViewDSResults.getSelectionModel().getSelectedItems();

boolean removed = true;
for (Map item : items)
{
removed = tblViewDSResults.getItems().remove(item);
}

Method 2:

tblViewDSResults.getItems().removeAll(tblViewDSResults.getSelectionModel().getSelectedItems());
  • 1. Re: TableView Remove Item Error
    sselvia Newbie
    Currently Being Moderated
    Tried a diferent approach, I would still expect the Method 1 or 2 to work properly especially method 2. This seems to work consistently every time

    List<Integer> indices = tblViewDSResults.getSelectionModel().getSelectedIndices();
    ObservableList<Map> items = tblViewDSResults.getItems();

    for (int i = indices.size() - 1; i >= 0; i--)
    {
    items.remove(items.get(indices.get(i)));
    }
  • 2. Re: TableView Remove Item Error
    James_D Guru
    Currently Being Moderated
    The problem with your first approach is that you're getting a reference to the list of selected items. When you remove an item, that list will change. So as you progress through the loop (either explicitly in method 1 or implicitly in method 2), the item(s) you try to delete each time change.

    You can fix it with
    List<Map> items = new ArrayList<Map>(tblViewDSResults.getSelectionModel().getSelectedItems());
    and then either method will work.

    This is probably actually safer than using the list of selected indices, which has the potential to suffer from the same problem. That it works is only a result of the implementation of the selection model.

    Edited by: James_D on Jan 23, 2013 7:26 AM (Fixed horrible grammatical error)
  • 3. Re: TableView Remove Item Error
    sselvia Newbie
    Currently Being Moderated
    Thanks, worked great.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points