user1768830
user1768830

Reputation:

How does MVC/MVP work in a Swing app?

I have been asked to revamp an existing JDialog that is a child container of an in-house Swing app. I will be re-writing the dialog from scratch and have been asked to lead the charge towards making the Swing app resemble a true MVC/MVP architecture (so my JDialog revamp will be the first of many pro-MVC changes to the app itself).

I understand MVC/MVP as it pertains to web apps:

This is not how all MVC/MVP web frameworks operate, but is the general idea.

But I'm struggling trying to determine how to translate this to a Swing app. In the Swing app, you have:

So I ask: how do I organize all the code necessary for a functioning JDialog using an MVC/MVP architectural pattern? Also, if there are any articles, tutorials, or existing open souce projects that showcase MVC/MVP Swing apps, I am interested in them as well. Thanks in advance!

Upvotes: 1

Views: 1420

Answers (3)

splungebob
splungebob

Reputation: 5415

Since there are many valid recipes out there, I'll only discuss what I use: a modified MVP design which also borrows ideas from The Humble Dialog Box.

Basically, create your GUI with as little application logic as possible (zero is the goal). Create "presenter" classes (similar to Controllers) that have a handle to the GUI and inject the appropriate listeners onto the UI.

Some benefits:

  1. Since all application code is out of the UI, your code is now 100% testable.
  2. You can quickly prototype your GUI without having to launch your app everytime, which can be a big time-saver.
  3. Separation of concerns makes code easier to read/maintain.
  4. Your GUI code will be Swing only. A new team member who isn't familiar with your app but is familiar with Swing can jump right in.

With regard to Swing's implementation of MVC, we actually don't care. That's Swing's business. We assume Swing works (which it usually does). True, we need to know these sorts of things for writing custom renders, editors, models, etc., but those are details that the application framework (which is what I think you're asking about) doesn't need to know or care about, for the most part.

Upvotes: 1

trashgod
trashgod

Reputation: 205785

As discussed here, Swing MVC hinges on the observer pattern used to propagate model changes back to any listening view(s). As a result, much depends on the components in your JDialog. If your dialog must be modeless, the examples here and here may be helpful.

Upvotes: 1

user529543
user529543

Reputation:

I would do like this:

MyModel model = engine.getDataFromDatabase();
myController.displayDataOnMyCustomView(myPresenter, model);

And at controller side, probably will remove a lot of listeners, set the data based on model, set sizes, locations and any other state representing stuff and finally re-add the listeners.

The myPresenter should be a custom JDialog with various basic ui elements (Component)on his UI tree.

Upvotes: 0

Related Questions