user3932611
user3932611

Reputation:

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!!

Upvotes: 0

Views: 328

Answers (3)

camickr
camickr

Reputation: 324098

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.

Upvotes: 1

dryairship
dryairship

Reputation: 6077

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.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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

@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.

Upvotes: 2

Related Questions