When the user closes my program, the program needs to shut down some background processes that might take a while to shutdown. So I want the user to be notified with a message box appearing and informing the user, and then when the background processes are all done, the message box should disappear.
An example of something similar to this i开发者_如何学Cs when you close Eclipse a message box will appear, notifying the user that the environment is being saved along with other shutdown processes.
How could I go about doing this?
You can add a WindowListener to your top level JFrame, listen for the windowClosing event, and then pop up a dialog box. In terms of making the dialog dismiss itself, you'll probably want to use a JProgressBar to inform user how much time is left (see this tutorial). Assuming you're using a SwingWorker, you can have the SwingWorker doing the work call the dispose method of the JDialog when it's finished processing (within its done method).
You could create a modal java.swing.JDialog
with a ProgressBar
It's actually easier than you might think. To capture the window closing event, you need to addWindowListener(WindowListener wl)
to the JFrame in question. Then, you can override the WindowClose method in whatever class you like, allowing you to customize the functionality accordingly.
I found this just now at this link.
Although presented solutions are quite clean, they're however not very efficient, as by only listening to main JFrame, you won't have the opportunity to use it for other closing mechanisms (think about Alt+F4
, Ctrl-C
in command line and others).
To my mind, one would have better registering a shutdown hook that both shows the message dialog and performs the shutdown operations. This way, whatever way the user choose to close the application, all shutdown operations will be correctly performed.
精彩评论