Hi there,
in my application the user can load some files from disk. The loading is done in a separate thread spawned just for that purpose. At the same time a JDialog is created to show the progress of the loading.
This works great and all, but there is one problem, I want to give the user the possibility to close the JDialog and stop the loading of resources.
Now, I dont know how to properly kill the thread in such an event.
I will show some code:
// Creates a new project. The project has not become the current project of the application yet. final Project project = new Project(); project.setProjectPath(projectPath); // Creates the JDialog used to show the progress final DialogProgress progressDialog = new DialogProgress(this); progressDialog.setProject(project); // This thread will load the resources, dispose the dialog when all resources have been loaded, and make the project current in this application Thread loadingThread = new Thread() { public void run() { project.load(); progressDialog.dispose(); setProject(project); } }; // Start thread and show dialog loadingThread.start(); progressDialog.setVisible(true);
My plan was to add a WindowListener to my JDialog to find out when the window is closing.
Perhaps something like this:
final Project project = new Project(); project.setProjectPath(projectPath); final DialogProgress progressDialog = new DialogProgress(this); progressDialog.setProject(project); final Thread loadingThread = new Thread() { public void run() { project.load(); progressDialog.dispose(); setProject(project); } }; // Makes sure the thread is stopped when the progress dialog was closed. progressDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { loadingThread.stop(); // The default close operation for the dialog is "DO_NOTHING_ON_CLOSE". progressDialog.dispose(); } }); loadingThread.start(); progressDialog.setVisible(true);
But this is probably not a nice solution and I am afraid that files opened by the project might not be closed correctly.
Any suggestions? I really appreciate the help.