0

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?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • You cannot use a shutdown hook for this, Swing will not necessarily be there to display anything. There is also an issue that you need to run **all** GUI code on the EDT - your shutdown hook violates this rule. As far as running code on shutdown - anything wrong with writing a `shutdown()` method and calling that? Or add an `onClose` listener to your main frame? – Boris the Spider May 17 '14 at 16:58
  • Nothing wrong with the possible alternatives you mentioned, I was curious to know if there was any way to do that with a shutdown-hook. Thanks for your answer man. – user3648026 May 17 '14 at 19:12

1 Answers1

0

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.

Volodymyr Levytskyi
  • 3,364
  • 9
  • 46
  • 83