I have a custom editable table cell for my table view. Now, the issue I have is that the commitEdit()
function gets executed when the table is created. The issue is that it slows down the program as I'm updating items in my database and every single item gets updated.
public class ChoiceBoxCell extends TableCell<Student, Classroom> {
ChoiceBox<Classroom> classroomChoiceBox;
public ChoiceBoxCell(ObservableList<Classroom> classroomObservableList) {
classroomChoiceBox = new ChoiceBox<>();
classroomChoiceBox.setItems(classroomObservableList);
classroomChoiceBox.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null) {
processEdit(newValue);
}
});
}
private void processEdit(Classroom value) {
commitEdit(value);
classroomChoiceBox.setValue(value);
setGraphic(classroomChoiceBox);
}
@Override
public void cancelEdit() {
super.cancelEdit();
setGraphic(classroomChoiceBox);
}
@Override
public void commitEdit(Classroom value) { // gets executed on start up
super.commitEdit(value);
Student student = (Student) getTableRow().getItem();
student.setClassroom(value);
new StudentDao().updateStudent(student); // students get updated for no reason
classroomChoiceBox.setValue(value);
setGraphic(classroomChoiceBox);
}
@Override
public void startEdit() {
super.startEdit();
Classroom value = getItem();
if (value != null) {
classroomChoiceBox.setValue(value);
setGraphic(classroomChoiceBox);
}
}
@Override
protected void updateItem(Classroom item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
classroomChoiceBox.setValue(item);
setGraphic(classroomChoiceBox);
}
}
}
EDIT: Solution - thanks to @James_D
classroomChoiceBox.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null && newValue != getItem()) {
processEdit(newValue);
}
});