table.setOnMouseClicked(new EventHandler<javafx.scene.input.MouseEvent>() {
establece el controlador de clic para el conjunto TableView
en su lugar. De esta manera no se puede distinguir entre las columnas que se ha hecho clic.
Se debe utilizar la función de edición proporcionada por TableCell
su lugar:
// Simplified Person class
public class Person {
private final StringProperty name;
private final StringProperty email;
public Person(String name, String email) {
this.email = new SimpleStringProperty(email);
this.name = new SimpleStringProperty(name);
}
public final String getEmail() {
return this.email.get();
}
public final void setEmail(String value) {
this.email.set(value);
}
public final StringProperty emailProperty() {
return this.email;
}
public final String getName() {
return this.name.get();
}
public final void setName(String value) {
this.name.set(value);
}
public final StringProperty nameProperty() {
return this.name;
}
}
TableView<Person> table = new TableView<>(FXCollections.observableArrayList(
new Person("Darth Vader", "[email protected]"),
new Person("James Bond", "[email protected]")));
table.setEditable(true);
Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory = col
-> new TableCell<Person, String>() {
{
// make cell itself editable
setEditable(true);
}
@Override
public void startEdit() {
super.startEdit();
// open dialog for input when the user edits the cell
TextInputDialog dialog = new TextInputDialog(getItem());
dialog.setGraphic(null);
dialog.setHeaderText("Set new " + col.getText() + ".");
dialog.setTitle("Edit " + col.getText());
Optional<String> opt = dialog.showAndWait();
if (opt.isPresent()) {
commitEdit(opt.get());
} else {
cancelEdit();
}
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : item);
}
};
TableColumn<Person, String> name = new TableColumn<>("name");
name.setCellValueFactory(p -> p.getValue().nameProperty());
name.setCellFactory(cellFactory);
TableColumn<Person, String> email = new TableColumn<>("email");
email.setCellValueFactory(p -> p.getValue().emailProperty());
email.setCellFactory(cellFactory);
table.getColumns().addAll(name, email);