HpTerm
HpTerm

Reputation: 8281

Swing Worker Thread : Inner class vs passing parameter

I know SO is for specific questions but I need an advise on what is the correct practice in Java for working with swing worker thread.

My application generates large HTML text in response to a calculation process which is is displayed in a jTextPane. To avoid blocking the GUI I used to do the calculation in a Swing Worker Thread.

My problem is the following to start the calculation I need plenty information available in different menus checkboxes and listbox of the GUI, and at the end of the calculation I need to start functions within the EDT.

Here are 2 possibilities for me :

First one is to send plenty of information to my Swing Worker and also need to pass the MainFrame to access specific functions in the "done()"

public class MyWorker extends SwingWorker<Void, Void> {      

    private MyMainFrame frame;
    public MyWorker(plenty of params) {
    }

    @Override
    public Void doInBackground() {
        //my background process
    }

    @Override
    public void done() {
    frame.myfunc1;
    frame.myfunc2;
    frame.myfunc3;
    }
}

Second one would be to use a Inner Class

Which one is correct to do in Java. If both are "correct" what are the pros and cons of one against the other.

Upvotes: 3

Views: 1366

Answers (2)

Robin
Robin

Reputation: 36621

If it is the large amount of parameters you have to pass in the constructor that is bothering you, you can group those parameters in a container object and just pass the container (e.g. a MyWorkerContext class).

I personally would try to avoid passing the UI (elements) itself, but rather pass a model/stream/... which will be updated by the SwingWorker, allowing me to refactor the UI later on without having to fiddle with my SwingWorker class.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692121

Both approaches are OK. The advantage of an inner class is that it has access to the internals of the enclosing object. The disadvantage is that it's not reusable in another context (another frame which would have a similar interface, for example).

Just make sure your code is well structured and readable. For example, you might want to extract the three method calls in your done() method in a single method of the frame.

Upvotes: 2

Related Questions