Java GUI threads - SwingWorker

喜夏-厌秋 提交于 2019-12-18 09:31:26

问题


I have a question regarding SwingWorker and Java GUI's.

I have several classes which process information, we can call them Foo1, Foo2, and Foo3. This processing can take a very long time.

These are all subclasses of Foo, however Foo is not called directly itself (the Foo[x] classes use methods inherited from Foo. In order to keep the EDT free to paint a progress bar, what is the best way to use SwingWorker when keeping my object hierarchy? Is it possible to have wrapper classes such as Foo1Worker extends SwingWorker and have its doInBackground() call Foo1.myProcessMethod()? Even though Foo1 does not extend SwingWorker, will this still work as I expect it to?

edit: to clarify my question, how can I make Foo[x] SwingWorkers even though they are already subclasses?


回答1:


I think the answer hinges critically on the type of data managed by Foo subclasses. If the results are homogeneous, just extend SwingWorker and instantiate concrete subclasses accordingly:

class Whatever {}

abstract class AbstractFoo extends SwingWorker<List<Whatever>, Whatever> {}

class Foo1 extends AbstractFoo {

    @Override
    protected List<Whatever> doInBackground() throws Exception {
        ...
    }
}

If each manages a different type, make the parent generic and instantiate each concrete subclass with the required type:

class Whatever {}
class Whichever {}

abstract class GenericAbstractFoo<T, V> extends SwingWorker<T, V> {}

class Foo2 extends GenericAbstractFoo<List<Whatever>, Whatever> {

    @Override
    protected List<Whatever> doInBackground() throws Exception {
        ...
    }
}

class Foo3 extends GenericAbstractFoo<List<Whichever>, Whichever> {

    @Override
    protected List<Whichever> doInBackground() throws Exception {
        ...
    }
}



回答2:


You'd need a SwingWorker if you needed to update GUI elements, e.g. calling routines such as SetText(). I've never thought about using them for non-GUI update tasks; I've always sub-classed Thread or implemented Runnable. I recommend that you try this with your Foo classes and see if the problem takes care of itself.



来源:https://stackoverflow.com/questions/3159547/java-gui-threads-swingworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!