How to delete row from table column javafx

我是研究僧i 提交于 2019-12-21 02:49:13

问题


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(.....

回答1:


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



回答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.



来源:https://stackoverflow.com/questions/34857007/how-to-delete-row-from-table-column-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!