Get Any/All Active JFrames in Java Application?

放肆的年华 提交于 2019-11-28 08:21:47

Frame.getFrames() returns an array of all frames.

Alternately as mentioned by @mKorbel, Window.getWindows() will return all windows - since Frame (& JFrame) extend Window that will provide all frames, and then some. It will be necessary to iterate them to discover which ones are currently visible.

mike rodent

I agree with Stefan Reich's comment.

A very useful method is Window.getOwnedWindows()... and one context where it is useful, if not essential, is TDD (Test-Driven Development): in an (integration) test, where you have various Window objects on display (JDialog, etc.), if something goes wrong before the test has finished normally (or even if it finishes normally), you will often want to dispose of subordinate windows in the tests' clean-up code. Something like this (in 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();
                    }
                }
            }
        }
    });
}

Frame.getFrames() will do your work.

From oracle Doc:

Returns an array of all Frames created by this application. If called from an applet, the array includes only the Frames accessible by that applet.

A simple example:

//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();
    }
}

Also you can use Window.getWindows() as others mentioned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!