简体   繁体   English

如何在打开新框架时关闭上一个框架

[英]How to close a previous Frame when a new Frame is opened

I am coding MVC. 我正在编码MVC。 In my controller i am listening to the action and if the user clicks a "SHOW-LIST" button i am making an instance of my view class which extends from JFrame and therein the view class i create a new JFrame. 在我的控制器中,我正在听操作,如果用户单击“ SHOW-LIST”按钮,则我将创建一个从JFrame扩展的视图类的实例,并在其中创建一个新的JFrame。 My problem is that if i click on SHOW-LIST button multiple times, i have the frame opened multiple time. 我的问题是,如果我多次单击“ SHOW-LIST”按钮,则框架多次打开。 Can somebody please tell me how can i do so so that once a new frame is about to open the old frame closes.. 有人可以告诉我我该怎么做,以便新框架即将打开时,旧框架关闭。

Controller 调节器

public void actionPerformed(ActionEvent event) {
  String viewAction = event.getActionCommand();
  ...
    if (viewAction.equals("SHOW-LIST")) {
      showListUI = new ShowListDialogUI(displayedCustomerList);
    }
}

View 视图

class ShowListDialogUI extends JFrame{
  public ShowListDialogUI (List<Customer> customerList) {
    ..
    // I am drawing it here
    ..
  }
}

Can somebody please tell me how can i do so so that once a new frame is about to open the old frame closes.. 有人可以告诉我我该怎么做,以便新框架即将打开时,旧框架关闭。

  • use CardLayout , then there no reason to playing with Top-Level Container s, put there required number of JPanels , then just to switch betweens JPanel views 使用CardLayout ,则没有理由使用Top-Level Container ,放置所需数量的JPanels ,然后仅在JPanel视图之间进行切换

  • as @trashgod notified, really not good idea, way 正如@trashgod通知的那样,真的不是个好主意

  • otherwise have to clean-up (remove all contents) uselless container, because Top-Level Containers never will be GC'ed 否则,必须清理(删除所有内容)无用的容器, 因为永远不会对顶级容器进行GC处理

Well, depends on the use case, but instead of closing the old one, and creating the new one, you could focus the existing one (and probably update data?). 好吧,这取决于用例,但是您可以关闭现有的旧的(而不是更新旧的)(而不是关闭旧的,然后创建新的)。

Your controller can manage the frames and keep track of it. 您的控制器可以管理帧并对其进行跟踪。 In the most easiest (and not recommended) way, you have a boolean "isFrameOpen". 以最简单(但不推荐)的方式,您有一个布尔值“ isFrameOpen”。 You set it to true if you open the frame, to false if you close it (your frame has to communicate with the controller then, or the controller has to know about the status of the frame at least). 如果打开框架,则将其设置为true;如果关闭框架,则将其设置为false(然后,框架必须与控制器进行通信,或者控制器必须至少了解框架的状态)。 If boolean is true, then focus/recreate it. 如果布尔值为true,则集中/重新创建它。 If false, create a new one. 如果为false,则创建一个新的。

In more advanced solutions, you can keep track over all frames with a map and you have to deal carefully with concurrent access. 在更高级的解决方案中,您可以使用地图跟踪所有框架,并且必须谨慎处理并发访问。

--tb --tb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM