简体   繁体   中英

GUI application shuts down before the Shutdown Hook message appears

Java newbie here. Here's the deal: I've got the following, simple shutdown-hook:

class SHook implements Runnable {
public void run() {
    System.out.println("SH is done.");
}
}

And I've got a GUI application with a TextArea were the output is redirected, so that the message shows up there. Its window listener is again really simple:

public class MyAdapter extends WindowAdapter {
public void windowClosing(WindowEvent w){
    System.exit(0);
}
}

As I close the GUI application with the [X] button, the message shows up for a split second before the whole thing shuts down. Nothing wrong here.

What I would like to do is: after the message has been printed, wait for a couple seconds, enough to clearly see that the message has been printed. Adding a sleep or wait or whatever to the run method doesn't seem to work as the application still closes immediately.

I'm guessing the shutdown-hook is actually doing its job properly, it's just that the application doesn't care and closes the GUI immediately, while my hook prints its message somewhere in the Java limbo.

Is that correct? If yes, is there any simple way to make sure the GUI application only closes after the shutdown-hook is done, without making the shutdown-hook a non-shutdown-hook?

On your JFrame call method:

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

Then make sure that your WindowAdapter is added to JFrame with method adWindowListener .

Then in windowClosing put some println to see when it's called and of course use System.exit(0) in windowClosing if you want frame to be closed.

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