Tableview使特定单元格或行可编辑

Tableview使特定单元格或行可编辑

问题描述:

有没有办法让JavaFX中只有特定的单元格或行可编辑 TableView

Is there any way to make only specific cells or rows editable in a JavaFX TableView?

row 0 = editable(false)
row 1 = editable(true)

我想在行0上放置最终数据,在第1行放置用户数据(来自编辑单元格)

I want to put final data on row 0 and user data(from editing cell) on row 1

这可能吗?

覆盖与 TableView updateIndex 方法/ code>以某种方式根据索引设置可编辑属性:

Override the updateIndex method of editable cells you use with your TableView in a way that that sets the editable property according to the index:

public class StateTextFieldTableCell<S, T> extends TextFieldTableCell<S, T> {

    private final IntFunction<ObservableValue<Boolean>> editableExtractor;

    public StateTextFieldTableCell(IntFunction<ObservableValue<Boolean>> editableExtractor, StringConverter<T> converter) {
        super(converter);
        this.editableExtractor = editableExtractor;
    }

    @Override
    public void updateIndex(int i) {
        super.updateIndex(i);
        if (i == -1)  {
            editableProperty().unbind();
        } else {
            editableProperty().bind(editableExtractor.apply(i));
        }
    }

    public static <U, V> Callback<TableColumn<U, V>, TableCell<U, V>> forTableColumn(
            IntFunction<ObservableValue<Boolean>> editableExtractor,
            StringConverter<V> converter) {
        return column -> new StateTextFieldTableCell<>(editableExtractor, converter);
    }

    public static <U> Callback<TableColumn<U, String>, TableCell<U, String>> forTableColumn(
            IntFunction<ObservableValue<Boolean>> editableExtractor) {
        return forTableColumn(editableExtractor, new DefaultStringConverter());
    }

}

使用示例:

以下示例允许编辑单元格,第二项,但只能编辑一次。

The following example allows to edit a cell, the second item, but only once.

@Override
public void start(Stage primaryStage) {
    TableView<Item<String>> tableView = new TableView<>(FXCollections.observableArrayList(
            new Item<>("0"),
            new Item<>("1")));
    tableView.setEditable(true);

    ObservableMap<Integer, Boolean> editable = FXCollections.observableHashMap();
    editable.put(1, Boolean.TRUE);

    TableColumn<Item<String>, String> column = new TableColumn<>();
    column.setOnEditCommit(evt -> {
        editable.remove(evt.getTablePosition().getRow());
    });
    column.setCellValueFactory(new PropertyValueFactory<>("value"));
    column.setCellFactory(StateTextFieldTableCell.forTableColumn(i -> Bindings.valueAt(editable, i).isEqualTo(Boolean.TRUE)));
    tableView.getColumns().add(column);

    Scene scene = new Scene(tableView);

    primaryStage.setScene(scene);
    primaryStage.show();
}