java 如何从表列javafx中删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34857007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:27:34  来源:igfitidea点击:

How to delete row from table column javafx

javajavafxtablecolumn

提问by Pim

enter image description here

在此处输入图片说明

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

这些是我的表列CourseDescription。如果单击一行(该行变为“活动”/突出显示),并且他们按下“删除”按钮,它应该删除该行,我该怎么做?

The code for my Coursecolumn: (and what event listener do I add to my deletebutton?)

我的课程列的代码:(以及我要向删除按钮添加什么事件侦听器?)

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

回答by James_D

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

回答by P. Jowko

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:

首先,我们需要更改表中的 SelectionMethod 以允许多选:

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.

我们可以调用 removeAll 方法而不是 remove(也无需创建新集合),但这种解决方案不仅会删除选定的项目,还会删除它们的重复项(如果它们存在且未被选中)。如果您不允许表中出现重复项,您可以简单地使用 selectedRows 作为参数调用 removeAll。