Search code examples
javaswingworker

SwingWorker: How to delegate values from the process() method to another class


In my program I have a swingworker, so that the user can access the GUI while the program itself is still running.

Is there a way to return the values I declare in the process() method to another class? The reason I ask is the following:

The GUI shows among other things charts, which should update if the user pushes on a button. Within the doInBackground() method an ArrayList is permanent updated. In this ArrayList are values that the charts should show, so every time the user pushes the button the chart should show the values that are actually in the Array List

The code is the following

 protected Void doInBackground()
{
    SaveList savelist = new SaveList();


    while(true)
    {
     try
     {
            savelist.updateSaveList();
            publish((SaveList) savelist);

            Thread.sleep(100);
     }

     catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}



    protected void process(SaveList savelist) 
    {
     this.savelistsize = savelist.saveListSize();
     this.trueLabeled = savelist.trueLabeled();
     this.falseLabeled = savelist.falseLabeled();
     this.trueLabeledPercent = savelist.trueLabeled()/savelist.saveListSize();
     this.falseLabeledPercent = savelist.falseLabeled()/savelist.saveListSize();
    }`

Solution

  • If I understand you correctly, you want to delegate some of the logic done in process() to a different class. In that case make a named subclass of the SwingWorker and initialize it with the delegate instance.

    Example:

    public class MySwingWorker extends SwingWorker<Void, X> { // X - I don't know the type of SaveList elements
    
        private MyDelegate delegate;
    
        public MySwingWorker(MyDelegate delegate) {
            this.delegate = delegate;
        }
    
        protected Void doInBackground() { ... }
    
        protected void process(SaveList savelist) {
            delegate.doSomethingWith(savelist);
        }
    }
    

    and you can then implement your logic in MyDelegate.doSomethingWith(SaveList)