Search code examples
javamultithreadingswingthread-safetyswingworker

Updating Swing GUI while waiting for a thread to finish


I have a swing application with a Thread class running to do a specific Job. I need in a certain moment to stop the running thread. so i put a boolean inside the thread and when i set it to true the thread will be stopped.

The problem is that the thread take some time to finish the inside job it is doing.

I need to prevent the user to do any action on the GUI until the thread is finished. I tried something like setEnabled(false) but the application is freezing and GUI is not changed until the thread is stopped. I tried also to update the GUI in another thread but this is also does not work.

Is there any way to update the GUI or make the application like disabled while the delay of the stopped the thread is finsihed.

Thanks


Solution

  • Better you use SwingWorker :

    button.setEnabled(false);
    ...    
    @Override
    protected String doInBackground() throws Exception {
        // process related code
        return "";
    }
    
    @Override
    protected void done() {
        button.setEnabled(true);
    }
    

    The done() method will be called after finishing the process of doInBackground() method.