6

enter image description here

These are my table columns Course and Description. If one clicks on a row (the row becomes 'active'/highlighted), and they press the Delete button it should remove that row, how do I do this?

The code for my Course column: (and what event listener do I add to my delete button?)

@SuppressWarnings("rawtypes")
TableColumn courseCol = new TableColumn("Course");
courseCol.setMinWidth(300);
courseCol.setCellValueFactory(new PropertyValueFactory<Courses, String>("firstName"));

final Button deleteButton = new Button("Delete");

deleteButton.setOnAction(.....
Pim
  • 138
  • 1
  • 1
  • 6
  • 1
    As an aside: don't suppress raw types: use the correct type for your table column and table view. – James_D Jan 18 '16 at 14:24

2 Answers2

25

Just remove the selected item from the table view's items list. If you have

TableView<MyDataType> table = new TableView<>();

then you do

deleteButton.setOnAction(e -> {
    MyDataType selectedItem = table.getSelectionModel().getSelectedItem();
    table.getItems().remove(selectedItem);
});
James_D
  • 201,275
  • 16
  • 291
  • 322
2

If someone want to remove multiple rows at once, there is similar solution to accepted:

First we need to change SelectionMethod in our table to allow multiple selection:

table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

After this, we need to set action with such code for button:

ObservableList<SomeField> selectedRows = table.getSelectionModel().getSelectedItems();
// we don't want to iterate on same collection on with we remove items
ArrayList<SomeField> rows = new ArrayList<>(selectedRows);
rows.forEach(row -> table.getItems().remove(row));

We could call removeAll method instead of remove(also without creating new collection), but such solution will remove not only selected items, but also their duplicates if they exists and were not selected. If you don't allow duplicates in table, you can simply call removeAll with selectedRows as parameter.

P. Jowko
  • 111
  • 6