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



在这里,我想打开一个包含错误消息的DialogFrame,当buttonGroup未处于活动状态且单击搜索按钮时。因此,在ActionEvent中,我进行了DialogFramesetVisible(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);

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

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

最新更新