Connor Neville
Connor Neville

Reputation: 1078

Get Any/All Active JFrames in Java Application?

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.

Upvotes: 21

Views: 16092

Answers (3)

Blasanka
Blasanka

Reputation: 22447

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.

Upvotes: 0

mike rodent
mike rodent

Reputation: 15692

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

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168845

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.

Upvotes: 34

Related Questions