【问题标题】:How can I set visible to hide the jDialog (inside if condition) that is set visible shown (outside if loop)?如何设置可见以隐藏设置为可见的 jDialog(在 if 条件内)显示(在 if 循环之外)?
【发布时间】:2018-06-06 16:48:06
【问题描述】:

我想在buttonGroup 未激活且单击搜索按钮时打开包含错误消息的DialogFrame。所以在 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();
    }
}                                             

【问题讨论】:

  • JDialog 是模态的吗?如果是这样,那么它将在设置为可见后阻塞代码流。
  • 为什么默认设置为可见?为什么不sem.setVisible(bgGroup.getSelection() == null);
  • 1) 为了尽快获得更好的帮助,请发帖 minimal reproducible exampleShort, Self Contained, Correct Example。 2)对问题使用相关标签。 JDialog 标签是相关的,你的 IDE 的标签不相关。

标签: java swing visibility jdialog


【解决方案1】:

我建议不要操纵可见性,而根本不创建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();
}

【讨论】:

    【解决方案2】:

    保持简单。摆脱

    sem.setVisible(true);
    

    而只是做

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-07-11
      • 2013-02-02
      • 2020-02-28
      • 2015-08-22
      • 2019-09-24
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      相关资源
      最近更新 更多