问题
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