首页 > 解决方案 > 在其构造函数中处理框架

问题描述

当条件为真时,我想在其构造函数中放置一个框架。

this.dispose不是配置框架。我想要这样,当我的构造函数被调用时,如果条件 ie ( configurationBean.getCode().equals(macPass)) 为真,那么必须调用一个新框架并且必须关闭这个框架。否则必须创建此框架。

 public ConfigurationFrame() {
    String pcMac = getPcMacAddress();
    String macPass = getPassword(pcMac);
    ConfigurationDao configurationDao = new ConfigurationDaoImpl();
    ConfigurationBean configurationBean = configurationDao.checkCode(macPass);
    if(configurationBean == null)
        initComponents();
    else if(configurationBean.getCode().equals(macPass))
    {      
        new MainLoginFrame().setVisible(true);
        this.dispose();
        super.setVisible(false);
    }
}
}

标签: javaswingconstructorjframedispose

解决方案


请注意,您的问题是一个经典的“ XY 问题”类型问题,您会问“我如何做 X”,而最佳解决方案是“不要做 X,而是做 Y”。换句话说,您绝对想像您尝试做的那样在其构造函数中处置顶级窗口对象,例如 JFrame。

我认为您想要做的(猜测)是

  1. 测试事物的配置
  2. 如果确定,则显示主 GUI
  3. 如果不OK,则显示一个允许用户重新设置配置的窗口
  4. 关键点:然后重新测试配置是否OK,
  5. 如果是这样,则显示主 GUI
  6. 根据需要重复。

如果是这样,那么我将使用 while 循环显示设置配置窗口并在配置正常时退出循环,但如果用户只想退出或无法设置配置正常,也允许用户退出循环。像这样的东西:

// configurationGood: true if config is good
// justQuit: true if the user has had enough and wants to quit
while (!configurationGood && !justQuit) {
    // create configuration dialog here
    // calling constructors, and all
    // use a **modal** dialog here

    // change configurationGood and/or justQuit values in here
}

if (!justQuit) {
    // create and display main application here
}

注意

  • 此代码不在任何 GUI 窗口构造函数中调用,而是在显示 GUI 之前调用
  • 重新设置的配置窗口不应该是 JFrame 而是模态JDialog
  • 这样,程序代码流在显示对话框时暂停,并且仅在处理完对话框后恢复。
  • 这允许 while 循环中的代码查询对话框其字段的状态并使用它来重新测试配置是否正常

推荐阅读