Java – swingworker – we can call a swingworker from another swingworker instead of EDT

I have a swingworker as follows:

public class MainWorker extends SwingWorker(Void,MyObject) {
    :
    :
}

I called the above swing worker from EDT:

MainWorker mainWorker = new MainWorker();
mainWorker.execute();

Now, mainworker has created 10 instances of the mytask class so that each instance can run on its own thread to complete the work faster

But the problem is that I want to update the GUI from time to time when the task is running I know that if the task is executed by mainworker itself, I can use the publish () and process () methods to update the GUI

However, since the task is executed by a thread different from the swing worker thread, how can I update the GUI from the intermediate results generated by the thread executing the task

Solution

The API documentation for swingworker provides the following tips:

Mainworker can implement propertychangelister It can then register itself using propertychangesupport:

getPropertyChangeSupport().addPropertychangelistener( this );

Mainworker can provide its propertychangesupport object to each mytask object it creates

new MyTask( ...,this.getPropertyChangeSupport() );

The mytask object can then use propertychangesupport The firepropertychange method notifies its mainworker of progress or property updates

The notified mainworker can then use swingutilities Invoker or swingutilities Invokeandwait updates swing components through EDT

protected Void doInBackground() {
    final int TASK_COUNT = 10;
    getPropertyChangeSupport().addPropertychangelistener(this);
    CountDownLatch latch = new CountDownLatch( TASK_COUNT ); // java.util.concurrent
    Collection<Thread> threads = new HashSet<Thread>();
    for (int i = 0; i < TASK_COUNT; i++) {
        MyTask task = new MyTask( ...,latch,this.getPropertyChangeSupport() ) );
        threads.add( new Thread( task ) );
    }
    for (Thread thread: threads) {
        thread.start();
    }
    latch.await();
    return null;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>