Get Any/All Active JFrames in Java Application?

只谈情不闲聊 提交于 2019-11-27 02:10:12

问题


Is there a way from within a Java application to list all of the currently open/active (I'm not sure the terminology here) JFrames that are visible on screen? Thanks for your help.


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/7364535/get-any-all-active-jframes-in-java-application

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