从JavaFX TableView获取所选项目

问题描述:

如何从JavaFX中的 TableView 中获取所选项目?

How do I get the selected item from a TableView in JavaFX?

我目前正在使用

ObservableList selectedItems = taview.getSelectionModel().getSelectedItems();

但这不会返回选择模型中的一个选定项目。

but that does not return me the one selected item in the selection model.

好吧,假设您有一个名为 Person 的数据模型类。这样:

Ok, lets say you have a data model class named Person. This way:

Person person = taview.getSelectionModel().getSelectedItem();
System.out.println(person.getName());    

注意 TableView 必须带 Person 作为避免转换的类型参数:

Note that TableView must take a Person as a type argument to avoid casting:

@FXML
private TableView<Person> taview;

TableView<Person> taview = new TableView<>();

当您的行被选中时,您将返回一个实例。然后使用该实例做任何你想做的事。

when your row is selected, you will return one Person instance. Then do what ever you want with that instance.