简体   繁体   中英

Wait for Swing GUI to close before continuing

I am writing an app that requires the user to enter some data into a Swing GUI which the app will then use. After the user enters the data, there is no longer any need for the GUI as the app will then write some data to files.

The General idea is this:

launchGui();
closeGui();
continueWithComputation();

I understand that Swing uses a few threads in the background which I understand is why the program doesn't block until the GUI is closed.

Is it possible in any way to wait for the GUI to close (single JFrame closed with dispose() ) before continuing with continueWithComputation() ?

Wait for Swing GUI to close before continuing

Use a modal dialog. See the following for further details:

Is it possible in any way to wait for the GUI to close (single JFrame closed with dispose()) before continuing with continueWithComputation()?

  • user actions add WindowListener

  • from code to call JFrame#setVisible(false) , then you can running continueWithComputation() , you have to close this JVM by System.exit(0) , otherwise stays in PC's RAM untill restarted or power-off

I just had a similar problem, but without a closeGui() method and came up with this relatively short code snippet, using a WindowListener and some Java synchronization:

AtomicBoolean closed = new AtomicBoolean(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosed(WindowEvent e) {
        synchronized(closed) {
            closed.set(true);
            closed.notify();
        }
        super.windowClosed(e);
    }
} );

frame.setVisible(true);
synchronized(closed) {
    while (!closed.get()) {
        closed.wait();
    }
}

// executes after the Frame has been disposed

My suggestion is to open the JFrame GUI as Modal and then everything will wait until it disappears from the screen. As JFrame cannot be set as modal you have to open the GUI frame as JDialog. I am using:

public class frameMain extends JDialog{ 

be sure that into the constructor you use:

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Wherever you need to start the GUI frame you should use:

frameMain frm= new frameMain ();
frm.setModal(true);
frm.setVisible(true);

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