如何设置可见以隐藏设置为可见显示(在 if 循环外)的 jDialog(在 if 条件内)?

How can I set visible to hide the jDialog (inside if condition) that is set visible shown (outside if loop)?

这里我想打开一个 DialogFrame,其中包含一个 buttonGroup 未激活且单击搜索按钮时的错误消息。所以在 ActionEvent 中,我将 DialogFrame 设置为 setVisible(true)。但是当按钮组处于活动状态并且我单击搜索按钮(在 if 条件内)时,setVisible(false) 似乎不起作用,换句话说 DialogFrame 仍然弹出!

如何在 if 条件下关闭 DialogFrame 的可见性?

private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {                                              

    SrchEMsg sem = new SrchEMsg(this);
    sem.setVisible(true);
    sem.setLocationRelativeTo(null);
    sem.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);


    if (bgGroup.getSelection() != null) {
        sem.setVisible(false); //doesn't work.
        SrchResult sr = new SrchResult();
        sr.setVisible(true);
        sr.pack();
        sr.setLocationRelativeTo(null);
        sr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.dispose();
    }
}                                             

我建议不要操纵可见性,而只是根本不要创建 sem 如果 满足某些条件:

if (bgGroup.getSelection() == null) {
    // only handle `sem`
    SrchEMsg sem = new SrchEMsg(this);
    sem.setVisible(true);
    sem.setLocationRelativeTo(null);
    sem.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
} else {
    // only handle `sr`
    SrchResult sr = new SrchResult();
    sr.setVisible(true);
    sr.pack();
    sr.setLocationRelativeTo(null);
    sr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.dispose();
}

保持简单。干掉

sem.setVisible(true);

而是简单地做

sem.setVisible(bgGroup.getSelection() == null);

仅在需要时将其设置为可见

如果您希望在 用户做出选择时 设置对话框不可见,那么您不能在对话框创建代码中执行此操作,而是需要响应适当的事件,例如添加到 JRadioButtons 的 ActionListener 或 ItemListener。