当用户退出该组合框表格单元格的编辑模式时,您可以获取组合框选定值。即当新值被提交时。您需要使用tablecolumn.setOnEditCommit()
方法。这是一个完整的可运行的代码示例(MCVE为ComboBoxTableCell演示):
public class ComboBoxTableCellDemo extends Application
{
private TableView<Person> table = new TableView<>();
private final ObservableList<Person> data
= FXCollections.observableArrayList(
new Person("Bishkek"),
new Person("Osh"),
new Person("New York"),
new Person("Madrid")
);
@Override
public void start(Stage stage)
{
TableColumn<Person, String> cityCol = new TableColumn<>("City");
cityCol.setMinWidth(200);
cityCol.setCellValueFactory(new PropertyValueFactory<>("city"));
cityCol.setCellFactory(ComboBoxTableCell.<Person, String>forTableColumn("Bishkek", "Osh", "New York", "Madrid"));
cityCol.setOnEditCommit((TableColumn.CellEditEvent<Person, String> e) ->
{
// new value coming from combobox
String newValue = e.getNewValue();
// index of editing person in the tableview
int index = e.getTablePosition().getRow();
// person currently being edited
Person person = (Person) e.getTableView().getItems().get(index);
// Now you have all necessary info, decide where to set new value
// to the person or not.
if (ok_to_go)
{
person.setCity(newValue);
}
});
table.setItems(data);
table.getColumns().addAll(cityCol);
table.setEditable(true);
stage.setScene(new Scene(new VBox(table)));
stage.show();
}
public static class Person
{
private String city;
private Person(String city)
{
this.city = city;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
System.out.println("city set to new value = " + city);
this.city = city;
}
}
public static void main(String[] args)
{
launch(args);
}
}
如果事情按照通常的方式设置,当一个项目在组合框中选择,它会在该项目更新相应的属性表格行。因此,您只需查看表格的项目列表即可查看选定的值。 –