Оказалось, что это баг TableView
и висит он в багтрекере уже несколько лет. Нашёл обход. Выглядит как-то так:
import javafx.event.Event;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.util.StringConverter;
public class EditCell<S, T> extends TableCell<S, T> {
// Text field for editing
// TODO: allow this to be a plugable control.
private final TextField textField = new TextField();
// Converter for converting the text in the text field to the user type, and vice-versa:
private final StringConverter<T> converter ;
public Torte1(StringConverter<T> converter) {
this.converter = converter ;
itemProperty().addListener((obx, oldItem, newItem) -> {
if (newItem == null) {
setText(null);
} else {
setText(converter.toString(newItem));
}
});
setGraphic(textField);
setContentDisplay(ContentDisplay.TEXT_ONLY);
textField.setOnAction(evt -> commitEdit(this.converter.fromString(textField.getText())));
textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if (! isNowFocused) {
commitEdit(this.converter.fromString(textField.getText()));
}
});
textField.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ESCAPE) {
textField.setText(converter.toString(getItem()));
cancelEdit();
event.consume();
} else if (event.getCode() == KeyCode.RIGHT) {
getTableView().getSelectionModel().selectRightCell();
event.consume();
} else if (event.getCode() == KeyCode.LEFT) {
getTableView().getSelectionModel().selectLeftCell();
event.consume();
} else if (event.getCode() == KeyCode.UP) {
getTableView().getSelectionModel().selectAboveCell();
event.consume();
} else if (event.getCode() == KeyCode.DOWN) {
getTableView().getSelectionModel().selectBelowCell();
event.consume();
}
});
}
/**
* Convenience converter that does nothing (converts Strings to themselves and vice-versa...).
*/
public static final StringConverter<String> IDENTITY_CONVERTER = new StringConverter<String>() {
@Override
public String toString(String object) {
return object;
}
@Override
public String fromString(String string) {
return string;
}
};
/**
* Convenience method for creating an EditCell for a String value.
* @return
*/
public static <S> Torte1<S, String> createStringEditCell() {
return new Torte1<>(IDENTITY_CONVERTER);
}
// set the text of the text field and display the graphic
@Override
public void startEdit() {
System.out.println("Start Editing");
super.startEdit();
textField.setText(converter.toString(getItem()));
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
textField.requestFocus();
}
// revert to text display
@Override
public void cancelEdit() {
super.cancelEdit();
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
// commits the edit. Update property if possible and revert to text display
@Override
public void commitEdit(T item) {
System.out.println("Commit Edit");
// This block is necessary to support commit on losing focus, because the baked-in mechanism
// sets our editing state to false before we can intercept the loss of focus.
// The default commitEdit(...) method simply bails if we are not editing...
if (! isEditing() && ! item.equals(getItem())) {
TableView<S> table = getTableView();
if (table != null) {
TableColumn<S, T> column = getTableColumn();
CellEditEvent<S, T> event = new CellEditEvent<>(table,
new TablePosition<S,T>(table, getIndex(), column),
TableColumn.editCommitEvent(), item);
Event.fireEvent(column, event);
}
}
super.commitEdit(item);
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
Класс, расширяющий Application
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import java.util.function.Function;
@SuppressWarnings("unchecked")
public class TableTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
TableView tableView = new TableView();
tableView.getSelectionModel().setCellSelectionEnabled(true);
tableView.setEditable(true);
tableView.getColumns().add(createColumn("Name", Person::nameProperty));
tableView.getItems().addAll(
new Person("Carl"),
new Person("Jon")
);
tableView.setOnKeyPressed(event -> {
TablePosition<?, ?> pos = tableView.getFocusModel().getFocusedCell();
if (pos != null && event.getCode().isLetterKey()) {
tableView.edit(pos.getRow(), pos.getTableColumn());
}
});
Scene scene = new Scene(tableView);
primaryStage.setScene(scene);
primaryStage.setWidth(400);
primaryStage.setHeight(400);
primaryStage.setTitle("test");
primaryStage.show();
}
private <T> TableColumn<T, String> createColumn(String title, Function<T, StringProperty> property) {
TableColumn<T, String> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
col.setCellFactory(column -> EditCell.createStringEditCell());
return col;
}
public static class Person {
private final StringProperty name = new SimpleStringProperty();
public Person(String name) {
setName(name);
}
public final StringProperty nameProperty() {
return this.name;
}
public final void setName(final java.lang.String firstName) {
this.nameProperty().set(firstName);
}
}
public static void main(String[] args) {
launch(args);
}
}
Суть проблемы доступно объясняют на англоязычном Stack Overflow
Источником проблемы является TableCellBehaviour
, а именно, его
реакция на событие mousePressed
:
mousePressed
вызывает simpleSelect(..)
- При обнаружении одинарного клика, вызывается
edit(-1, null)
- который вызывает тот же метод в
TableView
- который приравнивает свой
editingCell
свойство null
tableCell
слушает это свойство и реагирует отменой изменения