带警报对话框的表中的侦听器

时间:2018-07-23 06:30:25

标签: java javafx

我有2个表,我想根据第一个表中选择的行来填充第二个表。在填充第二张表中的数据之前,我需要一个警报对话框,其中如果按下Yes,将在第一张表中选择新行,并填充数据,但是如果按下No,则将保留旧行在第一个表中。我怎样才能做到这一点?我尝试如下进行操作,但停留在第二部分。

table1.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
        if (newSelection != null) {


                    Alert alert = new Alert(AlertType.CONFIRMATION, "Unsaved Data Will be Deleted. Continue" + " ?",
                            ButtonType.YES, ButtonType.NO);
                    alert.showAndWait();
                    if (alert.getResult() == ButtonType.YES) {

                        //populate table2

                    } else if (alert.getResult() == ButtonType.NO) {
                        // Cancel New Selection and keep the old one
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {

                            //stuck here

                            // how to keep old one selected instead new
                         //table1.getSelectionModel().select(oldSelection); //falls in a infinte loop
                            //return;                       
                            }
                        });

                    }

                }


    });

1 个答案:

答案 0 :(得分:2)

不确定这是否有助于解决无限循环问题,但尝试进行到找到更优雅解决方案的过程不会有任何危害:

table1.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Foo>() {
    private boolean reverting = false;

    @Override
    public void changed(ObservableValue<? extends Foo> observable, Foo oldSelection, Foo newSelection) {
        if (newSelection != null && !reverting) {
            Alert alert = new Alert(AlertType.CONFIRMATION, "Unsaved Data Will be Deleted. Continue" + " ?",
                    ButtonType.YES, ButtonType.NO);
            alert.showAndWait();

            if (alert.getResult() == ButtonType.YES) {
                //populate table2
            }
            else if (alert.getResult() == ButtonType.NO) {
                 reverting = true;
                 table1.getSelectionModel().select(oldSelection);
            }
        }

        reverting = false;
    }
});