【问题标题】:Start application as Dialog that calls parent frame将应用程序作为调用父框架的对话框启动
【发布时间】:2015-07-07 17:16:18
【问题描述】:

情况如下:

我的应用由一个包含 x 元素的对话框和一个按钮组成。用户在与元素交互后按下按钮,如果他以特定方式进行交互,则只有对话框所在的父框架才会出现。

为此,我目前知道这种方法:

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(false);
                jDialog.setVisible(true);
            }
        });
    }

然后在位于 jDialog 内的 Button 上添加此命令:

new NewJFrame().setVisible(true);

这个技巧做得很好而且很简洁,但是之前使用 new NewJFrame().setVisible(false); 调用的实例仍在运行(据我所知)。

难道我不能在按钮(位于 jDialog 内)上执行此操作,就像使用类似:

NewJFrame.setVisible(true);

(它目前给我错误:Non-static method cannot be referenced from static context

【问题讨论】:

    标签: java swing jframe parent-child jdialog


    【解决方案1】:

    确保对话框是模态的,您可以这样做:

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewJFrame newJFrame = new NewJFrame();
                newJFrame.pack();
                // no need to set visible false. It already is
    
                MyDialog myDialog = new MyDialog(newJFrame); 
                // make sure the super constructor makes the dialog modal
    
                myDialog.pack();
                myDialog.setVisible(true);
    
                // here the dialog is no longer visible
                // and we can extract data from it and send it to the JFrame if needed
    
                newJFrame.setVisible(true); // ****** here
            }
        });
    }
    

    否则,如果您绝对必须在 JDialog 中处理 JFrame,只需将 NewJFrame 传递给 JDialog 的构造函数,因为它应该在 JDialog 超级构造函数中使用,所以您需要做的事情,使用它来设置 NewJFrame字段,然后在对话框内的实例上调用 setVisible(true)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多