首页 > 解决方案 > 带有警报对话框的表中的侦听器

问题描述

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

                    }

                }


    });

标签: javajavafx

解决方案


不确定这是否有助于防止无限循环,但在有人找到更优雅的解决方案之前尝试它没有害处:

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

推荐阅读