Search code examples
javaswinguser-interfacejlabelswingworker

Using Swingworker to constantly update a GUI


In my code, the user presses a button, and then I want this to invoke a SwingWorker background thread, where I basically loop through a list, cross reference it with other data, and then update the GUI with a JLabel for every pass through my loop. The problem is I know I should do this in doInBackground(), but I have nothing to return, and I also want to update the JPanel with a new JLabel every time my loop loops. How do I do this? Thanks!


Solution

  • Here is a complete example i really like Swing Worker Example

    You have to use publish() and override process()

    Example:

    class Worker extends SwingWorker<Void, String> {
    
        @Override
        protected void doInBackground() throws Exception {
           //here you make heavy task this is running in another thread not in EDT
           //process after some time call publish() 
    
    
        }
    
        @Override
        protected void process(List<String> chunks) {
            //this is executed in the EDT
            //here you update your label
        }
    }