如何动态地将 ArrayList 值加载到 JavaFx 中的可编辑 TableView 列单元格中

How to load dynamacilly an ArrayList value into editable TableView column cell in JavaFx

我正在尝试在可编辑单元格中加载具有 ArrayList 值的 TableView。我有以下 ReadOnlyStringWrapper 加载 ArrayList 但我需要可编辑,如何?

ObservableList<String> infoHeader = FXCollections.observableArrayList();
tableView = new TableView(FXCollections.observableArrayList(
        infoHeader));
tableView.setId("index-table");
TableColumn<String, String> headerColumn = new TableColumn<>("HEADER");
headerColumn.setCellValueFactory((p) -> {
    return new ReadOnlyStringWrapper(p.getValue());
});


tableView.getColumns().addAll(headerColumn);
tableView.setEditable(true);

请注意,这里不需要 ReadOnlyStringWrapper,因为您永远不会使用它提供的 ReadOnlyStringPropertySimpleStringProperty 就够了。

此外,这是不必要的:

ObservableList<String> infoHeader = FXCollections.observableArrayList();
...
FXCollections.observableArrayList(
        infoHeader)
...

它只是将空 ObservableList 的内容复制到新的 ObservableList。只需使用 FXCollections.observableArrayList() 作为第二个表达式即可达到相同的效果。


您可以使用 TableColumnonEditCommit 处理程序将值写入项目列表,但您还需要使用 returns 可编辑的 cellFactory单元格,例如 TextFieldTableCells。此外,每个项目仍然需要从代码中添加。

// data list with sample entry
ObservableList<String> infoHeader = FXCollections.observableArrayList("something");

tableView = new TableView<>(infoHeader);
tableView.setId("index-table");

TableColumn<String, String> headerColumn = new TableColumn<>("HEADER");
headerColumn.setCellValueFactory((p) -> {
    return new SimpleStringProperty(p.getValue());
});
headerColumn.setOnEditCommit(evt -> {
    // change list item corresponding to this cell
    evt.getTableView().getItems().set(evt.getTablePosition().getRow(), evt.getNewValue());
});
headerColumn.setCellFactory(TextFieldTableCell.forTableColumn());

tableView.getColumns().addAll(headerColumn);
tableView.setEditable(true);