Updating the GUI from a Running Thread
To update the GUI from a running thread, we use the second template parameter. We call the publish() method to ‘publish’ the values with which we want to update the user interface (which can be of whatever type the second template parameter specifies). Then we override the process() method, which receives the values that we publish.
Actually process() receives lists of published values, because several values may get published before process() is actually called.
In this example we just publish the latest value to the user interface.
SwingWorker<Boolean,Integer>worker=newSwingWorker<Boolean,Integer>(){@OverrideprotectedBooleandoInBackground()throwsException{// Simulate doing something useful.for(inti=0;i<=10;i++){Thread.sleep(1000);// The type we pass to publish() is determined// by the second template parameter.publish(i);}// Here we can return some object of whatever type// we specified for the first template parameter.// (in this case we're auto-boxing 'true').returntrue;}// Can safely update the GUI from this method.protectedvoiddone(){booleanstatus;try{// Retrieve the return value of doInBackground.status=get();statusLabel.setText('Completedwithstatus:'+status);}catch(InterruptedExceptione){// This is thrown if the thread's interrupted.}catch(ExecutionExceptione){// This is thrown if we throw an exception// from doInBackground.}}@Override// Can safely update the GUI from this method.protectedvoidprocess(List<Integer>chunks){// Here we receive the values that we publish().// They may come grouped in chunks.intmostRecentValue=chunks.get(chunks.size()-1);countLabel1.setText(Integer.toString(mostRecentValue));}};worker.execute();