Search code examples
javaswingmodel-view-controllerswingworker

Where should I invoke my swingworker in a Java MVC pattern


I have a program that is basically set up just like the one in this MVC example: http://www.leepoint.net/notes-java/GUI/structure/40mvc.html

In my program there is a process which takes quite a bit of time which freezes my GUI. I want to GUI to continuously update while the process is running. To do this I believe I need to use a SwingWorker. I don't know where in my MVC pattern I should be invoking this SwingWorker.

My thinking is that I should be running it in the MultiplyListener actionlistener of the controller. Would this be correct?


Solution

  • In this case, the model is a mathematical operation that evolves over time, perhaps by iteration. Clearly, the worker belongs in the model, as shown here. The setProgress() method will notify any PropertyChangeListener, and process() can notify any other listening view, as shown here.

    Addendum: In the second example, the worker updates a different model: the chart's dataset named collection. The chart, in turn, listens to the dataset and updates itself in response to the change.

    In the example cited, the controller installs action listeners on behalf of the model and view. In this related example, the GUI action listeners are local to their respective views. In either case, Action would be a suitable choice for encapsulation. The model notifies its observers when its internal state changes in response to user initiated actions.