CommitEdit function gets executed on creation of the table

泄露秘密 提交于 2019-12-13 09:07:17

问题


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

回答1:


Solution - thanks to James_D

classroomChoiceBox.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) -> {
        if (newValue != null && newValue != getItem()) {
            processEdit(newValue);
        }
    });


来源:https://stackoverflow.com/questions/41600356/commitedit-function-gets-executed-on-creation-of-the-table

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