Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - Java GUI threads - SwingWorker

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 {
        ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...