简体   繁体   中英

How to close the active JFrame

I am trying to find a method that can close the active JFrame.

I am unable to use frame.dispose(); , as I am declaring the action listener in a toolbar class and the frames I want to close are not static and are declared at runtime.

I have tried using:

java.awt.Window win[] = java.awt.Window.getWindows(); 
for(int i=0;i<win.length;i++){ 
win[i].dispose(); 
}

and whilst this does work, in certain circumstances it will close more than one window even though only 1 window appears to be open, so frames will flash open and closed many times depending on what actions the user has made.

For me to fully recreate my problem would involve posting a significant amount of code which would not be in line with MCVE principles.

I am hoping someone will know of a more simple and reliable way of closing the active frame in the mould of acitveframe.dispose(); - which I now is not a real solution!!

What happens if you try to get the Window ancestor of the source of the action event? ie,

@Override
public void actionPerformed(ActionEvent actionEvent) {
    Component comp = (Component) actionEvent.getSource();
    Window win = SwingUtilities.getWindowAncestor(comp);
    win.dispose();
}

This won't work if the source is not a Component or if it is not contained within the top level Window of interest.


Regarding:

For me to fully recreate my problem would involve posting a significant amount of code which would not be in line with MCVE principles.

I'll bet with a bit of effort you could create and post something that comes close.

I am hoping someone will know of a more simple and reliable way of closing the active frame

In your loop you can add:

if (window.isActive())
   // do something

Or maybe a simpler approach is:

Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();

Also, assuming your active window is a JFrame, instead of using window.dispose() , I have used code like:

WindowEvent windowClosing = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
frame.dispatchEvent(windowClosing);

this will simulate the user clicking on the "Close" button which means that any WindowListener you added to the frame will also be executed. See Closing an Appplication for more information and ideas.

When you are declaring your JFrames, declre them as final if you cannot use static :

final JFrame f = new JFrame();

It would solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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