It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes MVC in Swing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "MVC in Swing" Watch "MVC in Swing" New topic

MVC in Swing

Carlos Obregon

Joined: May 26, 2009
Posts: 18

I have used Java for a while but I'm not sure how to enforce MVC in a Swing application.

Normally I have a POJO's to represent the Model part and I have a main JFrame class which is also an ActionListener

My questions are: Do I create a single ActionListener to handle all events? Do I create an ActionListener that delegates based on the type of event? What happens if I also need a MouseListener?

Mo Jay
Ranch Hand

Joined: Feb 16, 2009
Posts: 83
Hello Carlos,

Using MVC in Swing requires some sort of registration for methods to be called upon when an event (action) takes place.

For example: you would want your action Listener methods to be located in the Controller class, and when the View notices an action (ex. button clicked) he (View) will call the appropriate method on the Controller. The controller accesses the model and possibly updating it in a way appropriate to the user's action, if the model has been updated, it notifies interested listeners of the change which is the Controller in this case.

You need to make sure that there is NO direct communication between the View and the Model, and all contacts go through the Controller.

You might want to implement Observer/Observable interfaces which allow you to register methods and notify parties when events take places.

Vish Shukla
Ranch Hand

Joined: Oct 12, 2008
Posts: 111

Take a look at HMVC pattern. It would be really maintainable and easy to use for Swing/ GWT applications.

HMVC Pattern

Thanks & Regards,
Vishal S Shukla (SCJP 93%, SCWCD 94%, SCBCD 100%)
I agree. Here's the link:
subject: MVC in Swing
It's not a secret anymore!