【问题标题】:Get Any/All Active JFrames in Java Application?在 Java 应用程序中获取任何/所有活动的 JFrame?
【发布时间】:2011-11-13 22:32:16
【问题描述】:

有没有办法从 Java 应用程序中列出屏幕上可见的所有当前打开/活动(我不确定这里的术语)JFrames?感谢您的帮助。

【问题讨论】:

  • 这具有明显的不良设计气味。应用程序中通常应该只有一个框架。如果创建了其他值得担心的顶级组件,请保留对它们的引用。
  • 你可能是对的,但我没有丰富的编程经验,我只是想测试一个替代想法。感谢您的评论和回答。
  • 我会稍微扩展一下该评论。一般是一个应用程序。会有1帧。使用任何数量的巧妙技术将多个组件塞入一个 GUI(例如 CardLayoutJSplitPaneJTabbedPaneJDesktopPane/JInternalFrame..)而无法包含在框架中的任何其他内容都可以显示在JDialogJOptionPane。第二个默认是模态的,而第一个可以指定为模态的。这意味着用户对父 JFrame 的输入在对话框打开时被阻止。对于获得更多输入等事情,模态非常方便。
  • 不,没有任何不好的气味。这是一个有效的设计选择。实际上,我们现在开始在 JavaX 中依赖它。

标签: java swing list methods jframe


【解决方案1】:

Frame.getFrames() 返回所有帧的数组。

正如@mKorbel 提到的那样,Window.getWindows() 将返回所有窗口 - 因为Frame (& JFrame) 扩展了Window,它将提供所有帧,然后是一些。有必要对它们进行迭代以发现哪些当前可见。

【讨论】:

    【解决方案2】:

    我同意 Stefan Reich 的评论。

    一个非常有用的方法是Window.getOwnedWindows()... 一个有用的上下文,如果不是必需的,是TDD(测试驱动开发):在一个(集成)测试中,你有各种Window对象在显示(JDialog 等)上,如果在测试正常完成之前出现问题(或者即使它正常完成),您通常会希望在测试的清理代码中处理从属窗口。像这样的东西(在 JUnit 中):

    @After
    public void executedAfterEach() throws Exception {
        // dispose of dependent Windows...
        EventQueue.invokeAndWait( new Runnable(){
            @Override
            public void run() {
                if( app.mainFrame != null ){
                    for( Window window : app.mainFrame.getOwnedWindows() ){
                        if( window.isVisible() ){
                            System.out.println( String.format( "# disposing of %s", window.getClass() ));
                            window.dispose();
                        }
                    }
                }
            }
        });
    }
    

    【讨论】:

      【解决方案3】:

      Frame.getFrames() 会做你的工作。

      From oracle Doc:

      返回此应用程序创建的所有框架的数组。如果调用 从小程序中,该数组仅包括可访问的帧 小程序。

      一个简单的例子:

      //all frames to a array
      Frame[] allFrames = Frame.getFrames();
      
      //Iterate through the allFrames array
      for(Frame fr : allFrames){
          //uncomment the below line to see frames names and properties/atr.
          //System.out.println(fr);        
      
          //to get specific frame name
          String specificFrameName = fr.getClass().getName();
      
          //if found frame that I want I can close or any you want
          //GUIS.CheckForCustomer is my specific frame name that I want to close.
          if(specificFrameName.equals("GUIS.CheckForCustomer")){
              //close the frame
              fr.dispose();
          }
      }
      

      您也可以像其他人提到的那样使用Window.getWindows()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-11
        • 2019-12-26
        • 1970-01-01
        • 2023-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多