Tableview make specific cell or row editable

本小妞迷上赌 提交于 2019-12-08 06:31:58

问题


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

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

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

Is this possible?


回答1:


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

}

Example use:

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


来源:https://stackoverflow.com/questions/39566975/tableview-make-specific-cell-or-row-editable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!