开发者

Java Backgroundworker: Scope of Widget to be updated unclear

开发者 https://www.devze.com 2022-12-24 10:04 出处:网络
I am trying to understand the mechanism of org.jdesktop.swingx.BackgroundWor开发者_开发百科ker. Their javadoc presents following example:

I am trying to understand the mechanism of org.jdesktop.swingx.BackgroundWor开发者_开发百科ker. Their javadoc presents following example:

final JLabel label;
class MeaningOfLifeFinder implements BackgroundListener {
    public void doInBackground(BackgroundEvent evt) {
        String meaningOfLife = findTheMeaningOfLife();
        evt.getWorker().publish(meaningOfLife);
    }

    public void process(BackgroundEvent evt) {
        label.setText("" + evt.getData());
    }

    public void done(BackgroundEvent evt) {}
    public void started(BackgroundEvent evt) {}
}

(new MeaningOfLifeFinder()).execute();

Apart from the fact that I doubt the result will ever get published, I wonder how label is passed to the process method, where it is being updated. I thought its scope was limited to the outside of the BackgroudListener implementation. Quite confused I am ... any answers for me?

Thanks in advance


This snippet is obviously out of date and incorrect; in addition, you have to put it back into some context (I guess MeaningOfLifeFinder is defined inside another class).

It won't compile because BackgroundListener doesn't exist (should be BackgroundWorker) and is a class not an interface, hence implements is incorrect here.

I think the snippet should read like:

class Something {
   final JLabel label;

   Something() {
       // Instantiate label here
   }

   class MeaningOfLifeFinder implements BackgroundWorker {
       public void doInBackground(BackgroundEvent evt) {
           String meaningOfLife = findTheMeaningOfLife();
           evt.getWorker().publish(meaningOfLife);
       }

       public void process(BackgroundEvent evt) {
           label.setText("" + evt.getData());
       }

       public void done(BackgroundEvent evt) {}
       public void started(BackgroundEvent evt) {}
   }

   void someAction() {
       (new MeaningOfLifeFinder()).execute();
   }
}

This should work better. In this case, you immediately see how the instance of MeaningOfLifeFinder will be able to access label (since it can access any member of its embedding class).

You just have to make sure that someAction() gets called somehow (eg from a user action).


I'm unfamiliar with BackgroundWorker, but it "is built upon SwingWorker." Absent setting an ExecutorService, BackgroundWorker defaults to SwingWorker, which may be a more accessible model for study. Compare the "two threads involved in the life cycle of a BackgroundWorker" with "SwingWorker which can operate with three."

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号