首页 > 解决方案 > 在 Vaadin 中打开新对话框时关闭对话框

问题描述

我在某个 UI 中创建了一个对话框。

Dialog dialog = new Dialog();
dia.add(new TestView());
dia.open();

新的 UI TestView 包含一个再次创建新对话框的按钮

private void button_onClick(ClickEvent<Button> event {
    Dialog dialog = new Dialog();
    dia.add(new TestView2());
    dia.open();
    ...
}

创建第二个对话框时如何关闭第一个对话框?

((Dialog)this.getParent()).close();不可能。

为了更好地理解: 图片

当 UiTwo 创建 UiThree 时,我希望关闭 UiTwo。这样总是只打开一个对话框。

标签: vaadin

解决方案


您的方法实际上是可能的,但请注意getParen()返回 a Optional<Component>,而不是 a Component。因此,您必须执行以下操作:

getParent().ifPresent(parent -> {
    if (parent instanceof Dialog) {
        ((Dialog) parent).close();
    }
});

或者如果你很勇敢

((Dialog) getParent().get()).close();

如果您想以参考方式进行操作,这是一种方式:

@Route
public class MainView extends VerticalLayout {

    public MainView() {
        Dialog dialog = new Dialog();
        dialog.add(new DialogView(dialog));
        dialog.open();
    }
}

和你的TestView2

public class DialogView extends VerticalLayout {

    public DialogView(Dialog dialog) {
        Button button = new Button("Next step");
        button.addClickListener(e -> {
            dialog.close();
            Dialog newDialog = new Dialog();
            newDialog.add(new Span("You are in the third step"));
            newDialog.open();
        });
        add(button);
    }
}

您甚至不必关闭第一个对话框,您只需替换内容即可

public class DialogView extends VerticalLayout {

    public DialogView(Dialog dialog) {
        Button button = new Button("Next step");
        button.addClickListener(e -> {
            dialog.removeAll();
            dialog.add(new Span("You are in the third step"));
        });
        add(button);
    }
}

如果您有许多想要像这样循环浏览的视图,我会创建一个抽象类来实现所有视图之间的通用功能。


推荐阅读