File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Swing and MVC design Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Swing and MVC design" Watch "Swing and MVC design" New topic

Swing and MVC design

Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
Would swing applications have classes called "controllers"? I've heard
that swing version of mvc is more a model delegate.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46405
Not sure about model delegates, but you do have control classes in Swing. You just call them ActionListeners or other Listeners.

If you have the ubiqitous calculator app you would have:
JFrame (V) with a Layout (V).
JButtons (V) for numbers +-*/ etc, with ActionListeners (C) registered to them.
JTextField (V) for result.
Calculating class (M) which does the work.
Some sort of class with main method to start it all off (M).

Was that of any help?

James Ridley

Joined: Apr 21, 2006
Posts: 15
Originally posted by Barry Brashear:
Would swing applications have classes called "controllers"? I've heard
that swing version of mvc is more a model delegate.


You could consider the core JFC componets of Swing as delegates as they are both the controller and the view. Take a JTextField as an example. It is used to display the information from the Document it is bound to, but also updates the document as the user enters data into the field.

Hari Surendran

Joined: Feb 09, 2003
Posts: 3
I feel the Swing framework itself is built on MVC framework and hence there, without doubt, are controllers. A view object such as Jtree has a corresponding TreeModel. But the controller code typically, in such cases, is part of the view class itself.

However if we are talking about a serious UI application, you must consider the MVC pattern with separate Model, View and Controller classes. A view object will be a java class that extend a JPanel(of course with other jpanels and text boxes, Combo boxes etc embedded). The model will be a java class with variables(to hold model data) and their getters and setters. The controller will be a third java class that will have various listeners etc that will have the controller logic. The controller logic could include state management, keeping the data in sync between view objects and model etc in addition to the classic controller job of listening to the user interaction and handling the user interaction logic.
I agree. Here's the link:
subject: Swing and MVC design
It's not a secret anymore!