【问题标题】:How to close only JDialog and have JFrame still usable如何仅关闭 JDialog 并让 JFrame 仍然可用
【发布时间】:2020-01-15 21:02:27
【问题描述】:

我有一个JFrame,并添加了一个JPanel。当我单击面板中的按钮时,会出现一个JDialog(名为choiceDialog)。当我单击对话框上的特定按钮时,我只想关闭它。

我希望对话框关闭并且框架可用。有可能吗?

我尝试使用setVisible(false) 隐藏对话框,但它同时隐藏了对话框和框架。然后我尝试做choiceDialog.dispose(),但我又失去了这两个元素。那时我找到了一种方法来设置 Frame 再次可见但不可用。

谁能帮帮我?我真的不知道该怎么办。

以下是相关代码:

if (dimField.isEnabled()){
    String dimFieldText = dimField.getText();
    if (dimFieldText.equals("") || !isNumeric(dimFieldText)){ //if there's an error when filling the options in the JDialog             
        errorLabel = new JLabel(noDim, SwingConstants.CENTER);
        /*other stuff
             ...
         */
    }else{ //if it's all ok: I want the JDialog close but the JFrame to be usable                   
        JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this); //to catch the JFrame istance
        choiceDialog.dispose();
        topFrame.setVisible(true); //to make the JFrame visible again
        //choiceDialog.setVisible(false);
    }

【问题讨论】:

  • topFrame.setVisible(true); //to make the JFrame visible again 为什么顶部框架一直设置不可见?我会制作对话框模式,并将框架指定为父级。这样,用户可以看到框架,但在对话框关闭之前不能与之交互。一般提示:为了尽快获得更好的帮助,edit 添加minimal reproducible exampleShort, Self Contained, Correct Example
  • 我看到您添加了“感兴趣的代码”(大多数人会称之为“相关代码”),但 MRE / SSCCE 更有用。创建一个应该只需要 20-40 行代码。
  • @AndrewThompson 是的,我的意思是“相关代码”。第二件事:我已经将对话框设置为模式(在我设置 JDialog 的方法中)。如何将框架指定为父级?我只找到了 getParent() 方法。
  • @AndrewThompson 这是我用来设置 JDialog 的代码:public void setChoiceDialog(String currentFile){ choiceDialog = new JDialog(); choiceDialog.setTitle("Impostazioni"); choiceDialog.setVisible(true); choiceDialog.setModal(true); choiceDialog.setLocationRelativeTo(null); choiceDialog.setLayout(new GridLayout(0,4)); choiceDialog.pack();}
  • @AndrewThompson 我发现了问题所在。这是 setModal() 属性。我刚刚删除了它,现在 JDialog 运行良好!谢谢你的建议。我将在接下来的问题中利用它们

标签: java swing jframe jpanel jdialog


【解决方案1】:

您将 topFrame 设置为按钮的窗口祖先,即对话框本身。您需要获取对话框的窗口祖先。这假设您在创建对话框时将主框架指定为其父框架,而不是使用无参数的 JDialog 构造函数。

【讨论】:

  • 好的,现在我在设置JDialog的方法中声明了topFrame,并将其作为JDialog构造函数的参数。我要做什么choiceDialog.getParent();
  • 我发现了问题。这是 setModal() 属性。我刚刚删除了它,现在 JDialog 运行良好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 2015-08-03
  • 1970-01-01
相关资源
最近更新 更多